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

14.3k views Asked by At

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)?

2

There are 2 answers

4
CubeJockey On BEST ANSWER

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.

0
hpopiolkiewicz On
while(leapYear<1750)

instead of:

if(leapYear<1750)