This is what you want to do :
public class TestLeapYear {
public static void main(String[] args) {
int year = 1900;
while (year <= 2100 ){
if (year % 4 == 0){
System.out.println(year + " Is a Leap Year");
year++;
}
else {
System.out.println(year + " Is not a leap year");
year++;
}
}
}
}
This code goes through all years from 1900 to 2100 and for each of them checks if it is a leap year (year%4==0). Then it prints accordingly.
Edit : you can also do it in one line using the ternary operator (condition ? doIfTrue: doIfFalse) (but it is less readable...)
public static void main(String[] args) {
int year = 1900;
while (year <= 2100 ){
System.out.println(year + " Is "+ ((year % 4 == 0)? "" : "not")+" a Leap Year");
year++;
}
}
In your original Code :
You are misusing the while loop. The principle of a while loop is to do the same thing until a condition is true.
So this :
while(condition){ doSomething()}
can be translated into : while the condition is true then I'll doSomething() when it's not true anymore I'll continue.
In your original code the condition is year <= 2100 && (year % 4 == 0)
so it is true only if the year is lesser or equal to 2100 AND the year modulo 4 equals 0. And this is this second condition that is false thus exiting the loop.
See how I used an IF ELSE statement inside the loop ? The loop is going through all the years and for each of them we test if it is a leap year of not.
About Leap Years :
Your way of determining if a year is a leap year is not complete. Wikipedia proposes a good algorithm :
if year is divisible by 400 then
is_leap_year
else if year is divisible by 100 then
not_leap_year
else if year is divisible by 4 then
is_leap_year
else
not_leap_year