我在Java代码中有一个while
循环:能否请您告诉我如何将其更改为for
循环。
我知道条件是rentalIterator.hasNext()
,然后执行while
循环。但是我不知道如何将其转换为for
循环。
它不显示迭代次数。但是在课堂出租中有3种情况。 这是否意味着迭代为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;
}
答案 0 :(得分:0)
public function up()
{
//Create the table
Schema::create('your_table_name', function (Blueprint $table) {
$table->bigIncrements('id')->unique();
$table->bigInteger('client_log_id');
$table->mediumText('partition_data');
$table->timestamps();
});
//Copy column from last table to new table
foreach(MyOldModel::all() as $item)
{
//now you can save old data into new table old data : $item -> log_data
//other operation you want
MyNewModel::create(array('partition_data' => $item -> log_data));//you can save other columns with adding array values
}
//Drop old table column
Schema::table('client_logs', function (Blueprint $table) {
$table->dropColumn('log_data');
});
}
答案 1 :(得分:0)
您可以执行以下操作:
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;
}
答案 2 :(得分:0)
好的,谢谢我的理解。这是迭代器的循环。因此,我们只是将定义和条件放入for循环条件中。抱歉,我忘记添加不完整的代码
Iterator rentalIterator = rentals.iterator();
所以在这里我们有答案:
for (Iterator rentalIterator = rentals.iterator();rentalIterator.hasNext();) {
double charge = 0;
Rental rental = (Rental) rentalIterator.next();
charge = rental.charge(charge, rental);
frequentRenterPoints = rental.frequentRenterPoints(frequentRenterPoints, rental);
result += rental.getDaysRented() +
" days of '" + rental.getMovie().getTitle() +
"' $" + String.valueOf(charge) + "\n";
totalAmount += charge;
}
谢谢你们
答案 3 :(得分:0)
在这里更具描述性, while 和 for 循环之间的基本区别之一是 while 使用条件进行迭代,其中用于使用一条语句。语句的格式通常为 for(initialization; condition; iteration),其中初始化和迭代都是可选的。
回到您的问题,有几种方法可以将while循环转换为for循环(如以上注释中所述),而最简单的方法之一就是只使用 condition for 循环中的 while 循环,格式为 for(; condition;) 在您的情况下,它将类似于:
for(;rentalIterator.hasNext();){
//your code
}