-2

Im making a program to read every user's input response inside a while loop to check if that year is a leap year or not. When I run it, the console tells me:

Exception in thread "main" java.util.NoSuchElementException

What does that mean and how could I fix the problem to get it running?

import java.util.Scanner;

public class GregorianCalendar {

    public static void main(String[] args) {

        int year, count, num;

        //How many different years to look at
        System.out.println("How many different years would you like to examine?"); 
        Scanner scan = new Scanner(System.in);
        count = scan.nextInt();
        scan.close();

        //Number of iterations
        num = 0;

        while (count != num) 
        {
            num++;

            System.out.println("Enter year");
            Scanner keyboard = new Scanner(System.in);
            year = keyboard.nextInt();
            keyboard.close();

            if (year % 400 == 0 || year % 4 == 0 && year % 100 != 0 && year > 1582) {
                System.out.println(year + " is a leap year!");
            }

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

            else {
            System.out.println("Error! " + year + " cannot be before the year 1582!");

            }
        }
    }
}
user207421
  • 305,947
  • 44
  • 307
  • 483
solorzke
  • 43
  • 1
  • 4

1 Answers1

-1

The problem you're having is that you're closing scanner and hence you're getitng an exception. Try this:

public static void main(String[] args) {

        int year, count, num;

        //How many different years to look at
        System.out.println("How many different years would you like to examine?"); 
        Scanner scan = new Scanner(System.in);
        count = scan.nextInt();

        //Number of iterations
        num = 0;

        while (count != num) 
        {
            num++;

            System.out.println("Enter year");
            year = scan.nextInt();

            if (year % 400 == 0 || year % 4 == 0 && year % 100 != 0 && year > 1582) {
                System.out.println(year + " is a leap year!");
            }

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

            else {
            System.out.println("Error! " + year + " cannot be before the year 1582!");

            }
        }

        scan.close();

    }

I'd also recommend to use just one Scanner like I have in the code.

Brunaldo
  • 324
  • 3
  • 11