Dear Readers, In this post I am going to show you how to write a core Java program to print Leap years!.
In this program, we will collect the start year and end year from the user and then find the leap years between the start and end year.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
/** * * @author agur */ import java.util.Scanner; public class PrintLeapYear { public static void main(String[] args) { int startYear, endYear, i; //create a scanner object to get the input Scanner in = new Scanner(System.in); //get the start year from user System.out.print("Enter the Start Year:"); startYear = in.nextInt(); //get the end year from user System.out.print("Enter the End Year:"); endYear = in.nextInt(); //print the leap years System.out.println("Leap years:"); //loop through between start and end year for (i = startYear; i <= endYear; i++) { //find the year is leap year or not, if yes print it if ( (0 == i % 4) && (0 != i % 100) || (0 == i % 400) ){ System.out.println(i); } } } } |
Just go through the comments to understand the above Java Program.
Sample output:
1 2 3 4 5 6 7 8 9 |
Enter the Start Year:1995 Enter the End Year:2015 Leap years: 1996 2000 2004 2008 2012 BUILD SUCCESSFUL (total time: 5 seconds) |
Enjoy Learning!