Java: List the leap years

Use a loop and a compound condition to find leap years in a range.

What to build

A program that lists the leap years between two years.

Requirements

  • Read two years a and b (a ≤ b).
  • Print the leap years from a to b inclusive, separated by spaces, on one line, then N leap years.
  • If there are none, print none on the first line.

Input

One line: a and b.

Output

Two lines.

Constraints

1 ≤ a ≤ b ≤ 10000.

Example

Input:

1996 2004

Output:

1996 2000 2004
3 leap years

Why it works

The rule needs && and || together: divisible by 4 but not by 100, unless divisible by 400, and the loop applies it to every year in the range.

Examples

Example 1 · Input
1996 2004
Expected output
1996 2000 2004
3 leap years
Example 2 · Input
1897 1903
Expected output
none
0 leap years

Hints

Hint 1

A year is a leap year if it is divisible by 4 and not by 100, or divisible by 400.

Hint 2

Loop from the first year to the last and print the ones that pass.

Solution

Show one correct solution (try it yourself first)
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int a = in.nextInt();
        int b = in.nextInt();
        StringBuilder out = new StringBuilder();
        int count = 0;
        for (int y = a; y <= b; y++) {
            if ((y % 4 == 0 && y % 100 != 0) || y % 400 == 0) {
                if (count > 0) out.append(" ");
                out.append(y);
                count++;
            }
        }
        System.out.println(count == 0 ? "none" : out.toString());
        System.out.println(count + " leap years");
    }
}

Lesson: Decisions and loops →