java - 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;
}
解决方案
你可以这样做:
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;
}
推荐阅读
- css - 触控笔创建多种样式,同时仅更改 1 个数组
- kubernetes - 每个节点的 CPU/内存请求和限制
- apache-kafka - 为什么 KafkaProducer 设计为线程安全的,而 KafkaConsumer 设计为线程不安全的?
- python - 播放声音和节目
- mysql - Mysql - 每天每小时获取唯一不同ip的计数
- typescript - TypeScript + react-native-sqlite-storage => 错误 TS2304:找不到名称“事务”
- python - Lambda 函数 - 如何将 python 代码拆分到多个文件中
- python - 在MATLAB中打开带有savemat编写的汉字的.mat文件时出错
- swift - 显示 viewController 时 Google 地图未正确居中
- android-studio - kotlin Android中除了枚举注解还有枚举的替代品吗?