Leap Year Calculator
The calculates if a year is a leap year by two methods in Java
1.) A leap year is a year that is divisible by 4 but not 100. If it’s divisible by 100, it has to be divisible by 400.
2.) Using the Year.isLeap function built into Java.
import java.time.Year;
public class leapYear {
public static void main(String[] args) {
LeapYear(1700);
LeapYear(1800);
LeapYear(1900);
LeapYear(2000);
LeapYear(1805);
LeapYear(-1600);
LeapYear(2017);
LeapYear(2024);
}
// Method 1 uses math method for leap year
public static void LeapYear(int year) {
System.out.println("Method 1");
if (year < 0) {
System.out.println(year + " Error: Not a Year\n");
}
if (year > 0) {
yearGTZero(year);
FuncIsLeapYear(year);
}
}
public static void yearGTZero(int year) {
int div4 = year % 4;
int div100 = year % 100;
int div400 = year % 400;
/*
Another way to put is:
A leap year is a year that is divisible by 4 but not 100.
If it's divisible by 100, it has to be divisible by 400.
*/
if (
((div4 == 0) && (div100 > 0)) ||
((div100 == 0) && (div400 == 0))
) {
printOut(year, true);
} else if (year > 0) {
printOut(year, false);
}
}
public static void FuncIsLeapYear(int year) {
// Method 2 uses Year.isLeap function
System.out.println("Method 2");
if (year < 0) {
System.out.println(year + " Error: Not a Year");
}
if (year > 0) {
printOut(year, Year.isLeap(year));
}
System.out.println();
}
public static void printOut(int year, boolean result) {
if (result) {
System.out.println(year + " is a leap year");
} else {
System.out.println(year + " not a leap year");
}
}
}
C:\Users\netadmin\.jdks\openjdk-23.0.1\bin\java.exe "-javaagent:C:\Program Files\JetBrains\IntelliJ IDEA Community Edition 2024.2.4\lib\idea_rt.jar=51102:C:\Program Files\JetBrains\IntelliJ IDEA Community Edition 2024.2.4\bin" -Dfile.encoding=UTF-8 -Dsun.stdout.encoding=UTF-8 -Dsun.stderr.encoding=UTF-8 -classpath C:\Users\netadmin\IdeaProjects\LeapYear\out\production\LeapYear leapYear
Method 1
1700 not a leap year
Method 2
1700 not a leap year
Method 1
1800 not a leap year
Method 2
1800 not a leap year
Method 1
1900 not a leap year
Method 2
1900 not a leap year
Method 1
2000 is a leap year
Method 2
2000 is a leap year
Method 1
1805 not a leap year
Method 2
1805 not a leap year
Method 1
-1600 Error: Not a Year
Method 1
2017 not a leap year
Method 2
2017 not a leap year
Method 1
2024 is a leap year
Method 2
2024 is a leap year
Process finished with exit code 0