Search code examples
javagregorian-calendarleap-year

Evaluate Multiple Years to Find a Leap Year Using a Boolean Utility Method


Good afternoon everyone, I am having an issue calculating multiple leap years from a boolean utility method. I've been told to use a loop, but have a hard time figuring out how and where to put it.

import java.util.Scanner;

 public class LeapYear {
      private static boolean isLeapYear(int year) {
          if (year % 400 == 0 && year % 100 == 0) {
              return true;
          }
          if (year % 100 == 0) {
              return false;
          }
          if (year % 4 == 0) {
              return true;
          }
          else {
             return false;
         }
     }
public static void main(String[] args) {
    int quitter = 0;
    int negative = 0;
    int year = 0;

    Scanner scan = new Scanner(System.in);

    System.out.println("Enter a year or -1 to quit: ");
    year = scan.nextInt();

    while (year != -1 && year < 1582) {
            System.out.print("The Gregorian calendar was not adopted until 1582, please enter a year after 1582: ");
            year = scan.nextInt();
    }

    if(year == -1) {
        negative += year;
        quitter++;
    }

    System.out.println(isLeapYear(year));
}

}


Solution

  • Just use a do-while loop:

    public static void main(String[] args) {
        int year = 0;
        Scanner scan = new Scanner(System.in); 
        do{
            System.out.println("Enter a year or -1 to quit: ");
            year = scan.nextInt();
            while (year < 1582) { 
                System.out.print("The Gregorian calendar was not adopted until 1582, please enter a year after 1582: ");
                year = scan.nextInt(); 
            } 
            if(year != -1) { 
                System.out.println(isLeapYear(year));
            } 
        }while(year!=-1);
    }