[英]java while loop inside or outside loop
I have the below code to show when the next leap year is. 我有以下代码显示下一个when年的时间。 In the while loop, I didn't have the line inside the while loop
leapYear = (((y % 4 == 0) && (y % 100 != 0)) || (y % 400 == 0))
at the first attempt. 在while循环中,我没有在while循环内找到该行
leapYear = (((y % 4 == 0) && (y % 100 != 0)) || (y % 400 == 0))
在第一次尝试。 My reason for not including that line was if leapYear false, y will plus 1. And then while (!leapYear)
condition is tested again using the new y value by plugging into the line above the while loop boolean leapYear = (((y % 4 == 0) && (y % 100 != 0)) || (y % 400 == 0))
. 我不包括该行的原因是,如果jumpYear为false,则y将加1。然后
while (!leapYear)
通过将新的y值插入到while循环上方的行中,再次测试while (!leapYear)
条件boolean leapYear = (((y % 4 == 0) && (y % 100 != 0)) || (y % 400 == 0))
。
I don't understand why I need to put that leapYear line in the while loop again. 我不明白为什么我需要再次在while循环中放入该jumpYear行。 I already had it above the loop which will be used to test the condition after
y++
since the while condition requires to test whether leapYear. 我已经在循环上方使用了它,它将用于测试
y++
之后的条件,因为while条件需要测试是否是否有jumpYear。
import java.util.Scanner;
public class NextLeapYear {
public static void main(String[] args) {
Scanner year = new Scanner (System.in);
System.out.print("Enter a year: ");
int y = year.nextInt();
boolean leapYear = (((y % 4 == 0) && (y % 100 != 0)) || (y % 400 == 0));
while (!leapYear) {
y++;
leapYear = (((y % 4 == 0) && (y % 100 != 0)) || (y % 400 == 0));
}
System.out.println("The next leap year is " + y + ".");
}
}
Because your y is changing inside the loop. 因为您的y在循环内变化。 leapYear depends on y so you need to re-calculate once y changes.
jumpYear取决于y,因此一旦y发生变化,就需要重新计算。
Since your Y Value Changes inside the loop so, for examples if 1994 is the value of Y. then it is a leapyear
, Then inside the loop it checks for not leapyear and value of y is pre incremented ++y
. 由于您的Y值在循环内更改,因此,例如,如果1994是Y的值,则它是一个
leapyear
,然后在循环内它不检查leap年,并且y的值预增加了++y
。 So, now if it is 1995, then it is tested for the condition, ie !leapyear and a while loop executes until it satisfies the condition, so until the next leapyear which is 1998. so then it terminates and prints the leapyear. 因此,现在如果是1995,则对条件进行测试,即!leapyear,并执行while循环,直到满足条件为止,因此直到下一个leap年,即1998年。因此,它将终止并打印the年。 Hope this helps.!
希望这可以帮助。!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.