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)?
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.
You could also try a
do-while
loop to cut down on repeated code:The user will just be reprompted to enter a year after 1750, which takes care of needing an error message.