Object-Oriented Programming with Java, part I – Exercise 21

This program determines whether the input year is a leap year or not.

My Code

import java.util.Scanner;

public class LeapYear {

    public static void main(String[] args) {
        Scanner reader = new Scanner(System.in);

        System.out.print("Type a year: ");
        int year = Integer.parseInt(reader.nextLine());

        if ((year % 4 == 0) && (year % 100 == 0) && (year % 400 == 0)) {
            System.out.println("The year is a leap year.");
        } else if ((year % 4 == 0) && (year % 100 == 0) && !(year % 400 == 0)) {
            System.out.println("The year is not a leap year.");
        } else if (year % 4 == 0) {
            System.out.println("The year is a leap year.");
        } else {
            System.out.println("The year is not a leap year.");
        }

    }
}

Model Code

import java.util.Scanner;

 

public class LeapYear {

 

    public static void main(String[] args) {

        Scanner reader = new Scanner(System.in);

 

        System.out.print("Type a year: ");

        int year = Integer.parseInt(reader.nextLine());

        if (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)) {

            System.out.println("The year is a leap year.");

        } else {

            System.out.println("The year is not a leap year.");

        }

    }

}

Comments

Not very well done on this one. It seems I like to go through each use case in if else statements whereas the model solution formulates it all into a one line expression. Very nice :).

Leave a Reply

Your email address will not be published. Required fields are marked *