java.time
The java.util
Date-Time API is outdated and error-prone. It is recommended to stop using it completely and switch to the modern Date-Time API*.
- You can use
java.time.Year#isLeap
to check if the year is a leap year.
- For testing, you can get the input from the keyboard using the
Scanner
class.
Demo:
import java.time.Year;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the first year: ");
int first = scanner.nextInt();
System.out.print("Enter the last year: ");
int last = scanner.nextInt();
System.out.println("Leap years between 1975 and 2015:");
for (int year = first; year <= last; year++) {
if (Year.of(year).isLeap()) {
System.out.println(year);
}
}
}
}
A sample run:
Enter the first year: 1975
Enter the last year: 2012
Leap years between 1975 and 2015:
1976
1980
1984
1988
1992
1996
2000
2004
2008
2012
Learn more about the modern Date-Time API from Trail: Date Time.
* For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7. If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.