'Evaluating multiple leap years
I need to modify this program I made that checks years if they are leap years. the modifications have to evaluate multiple years until the user wants to end by sentinel value. I also have to have each year to verify whether it is less than 1582 and say invalid or redirect to the error message again. been unsure of how i can accomplish this, thanks for any help that can be given
int year;
Scanner myScanner = new Scanner(System.in);
System.out.print("Please input year(s) (-1 to end): ");
year = myScanner.nextInt();
while (year != -1)
{
while (year < 1582)
{
System.out.print("Error (enter value greater than or equal to 1582 (-1 to exit to main): ");
year = myScanner.nextInt();
if (year >= 1582 || year == -1)
break;
}
if (year >= 1582)
if ((year % 4 != 0) || (year % 100 == 0 && year % 400 != 0))
System.out.print("Sorry, this value is not a leap year.");
else
System.out.print("This value is a leap year.");
break;
}
Solution 1:[1]
You're very close; an easier way to do this would be something like this.
Scanner myScanner = new Scanner(System.in);
System.out.print("Please input year(s) (-1 to end): ");
year = myScanner.nextInt();
for (; year != -1; year = myScanner.nextInt();
{
if (year < 1582)
{
System.out.print("Error (enter value greater than or equal to 1582, or -1 to exit to main): ");
continue;
}
if ((year % 4 != 0) || (year % 100 == 0 && year % 400 != 0))
System.out.print("Sorry, this value is not a leap year.");
else
System.out.print("This value is a leap year.");
System.out.print("Please input year(s) (-1 to end): ");
}
I think it's always tricky to get response loops correct and also looking nice. In this case, you were using break where I think you meant to use continue. You don't need a special loop for the error, though; you can do it by printing the error prompt and kicking it back to the main read loop.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | user2092266 |
