首页 > 解决方案 > How can I change this while loop to a for loop

问题描述

Here I have a while loop in java code: could you please tell me how can I change it to a for loop.

I know the condition is rentalIterator.hasNext(), then do the while loop. But I can't figure out how can I convert it to a for loop.

It doesn't show the number of iterations. But in class rental there are 3 cases. Does that means the iteratation for it is 3?

    public double daysRented(double charge, Rental rental) {
        switch (rental.getMovie().getPriceCode()) {
            case Movie.REGULAR:
                charge += 2;
                if (rental.getDaysRented() > 2)
                    charge += (rental.getDaysRented() - 2) * 1.5;
                break;
            case Movie.NEW_RELEASE:
                charge += rental.getDaysRented() * 3;
                break;
            case Movie.CHILDRENS:
                charge += 1.5;
                if (rental.getDaysRented() > 3)
                    charge += (rental.getDaysRented() - 3) * 1.5;
               break;
         }
         return charge;
    }
    while (rentalIterator.hasNext()) {
        double charge = 0;
        Rental rental = (Rental) rentalIterator.next();
        frequentRenterPoints = rental.frequentRenterPoints(frequentRenterPoints, rental) 
        result += rental.getDaysRented() + " days of '" + rental.getMovie().getTitle() + "' $" + String.valueOf(charge) + "\n";
        totalAmount += charge;
    }

标签: javaloopsfor-loopwhile-loop

解决方案


你可以这样做:

 for (Rental rental = (Rental) rentalIterator.next(); rentalIterator.hasNext(); )
            double charge = 0;
            frequentRenterPoints = 
            rental.frequentRenterPoints(frequentRenterPoints, rental) 
            result += rental.getDaysRented() +
            " days of '" + rental.getMovie().getTitle() +
            "' $" + String.valueOf(charge) + "\n";
            totalAmount += charge;
        }

推荐阅读