Cant figure out how to exit the loop of my program

后端 未结 3 2052
清酒与你
清酒与你 2021-01-25 22:00

I am writing a program for class that is a leap year checker. I have the loop working from what I understand however it goes into an infinite loop still? Zero wont terminate the

3条回答
  •  暗喜
    暗喜 (楼主)
    2021-01-25 22:26

    Your loop will only run if a user enters 0. And once they do, your program will be stuck in an infinite loop since you haven't changed the value of year inside your while.

    I'm assuming that you want to keep prompting the user to keep entering numbers until they enter 0? Then I would restructure your main method so that it surrounds the code where you retrieve and process input. Like so:

    System.out.println("Please enter a date to find out if the year is a leap year.");
    Scanner userInput = new Scanner(System.in);
    int year;
    
    do {
        year = userInput.nextInt();
    
        /**
         * Print some message based input. 
         */
    } while (year != 0); // Loop until user enters 0
    

提交回复
热议问题