Getting my program to go back to the "top" (if statement) (Java)

Idan Gelber picture Idan Gelber · Jun 18, 2015 · Viewed 11.5k times · Source

I have a program to calculate leap year, however, it only works past about the year 1750 so I want my user to only be able to input numbers past 1750.

System.out.println("Enter a year after 1750:");
    leapYear = in.nextInt();

    if(leapYear<1750){
        System.out.println("You have entered a year before 1750, please try again :");
        leapYear  = in.nextInt();
    }

My solution was to put a if statement. I realize, however, that this will only work if the user inputs something below 1750 once. if they do it again the program will move on. Is there a way I can execute the statement "You have entered a year before 1750, please try again :" as many times as I need to without re writing it?.

I was thinking maybe a while statement could work (if a while statement works how could I do it without causing an infinite loop)?

Answer

CubeJockey picture CubeJockey · Jun 18, 2015

You're on the right track with a while statement. It's pretty simple to keep it from executing infinitely. As soon as the user enters a correct year, the loop condition will evaluate to false and exit.

System.out.println("Enter a year after 1750:");
leapYear = in.nextInt();

while(leapYear < 1750){
     System.out.println("You have entered a year before 1750, please try again :");
     leapYear  = in.nextInt();
}

You could also try a do-while loop to cut down on repeated code:

do{
    System.out.println("Please enter a year after 1750:");
    leapYear = in.nextInt();
}while(leapYear < 1750);

The user will just be reprompted to enter a year after 1750, which takes care of needing an error message.