public class LeapYear_2 {
public static void main(String[] args) {
int year = 1900;
while (year <= 2100 && (year % 4 == 0)){
System.out.println(year + " Is a Leap Year");
year++;
System.out.println(year + " Is not a leap year");
year++;
}
}
}
I just want to know if whats wrong with my Codes? I want to create a program that year 1900 to 2100 will show the leap year and which is NOT.
I just dont know how to use while with many conditions... it seems that I have to have many conditions in while loop in order for this program to work as i want to.
This is what you want to do :
public class TestLeapYear {
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...)
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 :
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 :