Cant figure out how to exit the loop of my program

后端 未结 3 1991
清酒与你
清酒与你 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
    
    0 讨论(0)
  • 2021-01-25 22:35
    while (year == 0)
    {
        System.out.println();
    }
    

    There's your problem, if the year is 0, your program will infinitely output a new line.

    Furthermore, your ifs for checking if it is a leap year isn't inside the loop body, so even if you enter a non-zero number, the code will only run once.

    Try the following code, be sure to read the comments to understand what's going on:

    public static void main(String[] args)
    {
        Scanner in = new Scanner(System.in);
        int year = -1; //Give your int a default value so the main loop will execute
        while (year != 0) //-1 not equal to zero, so your code will start
        {
            System.out.print("Please enter a year: "); //Now we get the value of the year
            year = in.nextInt(); //Put it into our variable
            if (year < 1582) //And if it's less than 1582
            {
                if (year != 0)
                    System.out.println("Year must not be less than 1582!"); //Notify the user, unless they are exiting the program
                continue; //restart the while loop, this is quite a useful statement!
            }
            if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0) //Check if it's a leap year
                System.out.println("That is a leap year!\n"); 
            else
                System.out.println("That is not a leap year :(\n");
            //End of the loop, so it goes back to the beginning, which asks the user again for the year
            //So if you enter 0 next the program will close
        }
    }
    
    0 讨论(0)
  • 2021-01-25 22:39

    The first loop is infinite. You forgot to read the user input inside.

    0 讨论(0)
提交回复
热议问题