1. Introduction
Determining whether a year is a leap year is a common task in programming. A leap year occurs every 4 years to add an extra day to the calendar year, helping to keep our calendar in alignment with the Earth's revolutions around the Sun. However, simply being divisible by 4 does not guarantee that a year is a leap year. This blog post explains how to implement a Java program to check if a given year is a leap year, considering all the rules.
2. Program Steps
1. Import the Scanner class to read the year input from the user.
2. Prompt the user to enter a year.
3. Apply the leap year conditions to determine if the year is a leap year.
4. Display the result.
5. Close the Scanner object to prevent resource leaks.
3. Code Program
import java.util.Scanner;
public class LeapYearChecker {
public static void main(String[] args) {
// Create a Scanner object for reading input
Scanner scanner = new Scanner(System.in);
System.out.println("Enter a year:");
int year = scanner.nextInt(); // Read the year entered by the user
// Closing the scanner
scanner.close();
// Leap year conditions
if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)) {
System.out.println(year + " is a leap year.");
} else {
System.out.println(year + " is not a leap year.");
}
}
}
Output:
Enter a year: 2000 2000 is a leap year.
Explanation:
1. The program starts by importing the Scanner class for reading user input.
2. It prompts the user to enter a year, which is read from the console and stored in the year variable.
3. To determine if the year is a leap year, the program applies the following conditions: A year is a leap year if it is divisible by 4 but not by 100, except if it is also divisible by 400. This is implemented using an if-else statement that checks these conditions.
4. Depending on the outcome of the condition check, the program prints a message indicating whether the entered year is a leap year or not.
5. Lastly, the Scanner object is closed to avoid resource leaks. This program effectively demonstrates the use of conditional statements in Java to solve a problem based on specific rules.
Comments
Post a Comment
Leave Comment