简体   繁体   中英

java while loop inside or outside loop

I have the below code to show when the next leap year is. 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. 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)) .

I don't understand why I need to put that leapYear line in the while loop again. 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.

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. leapYear depends on y so you need to re-calculate once y changes.

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 . 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. Hope this helps.!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM