2016-10-17 5 views
-2

私は、whileループ内のすべてのユーザーの入力応答を読み込んで、その年がうるう年かどうかを確認するプログラムを作成します。私はそれを実行すると、コンソールが私に語った:ScannerとSystem.inを使用するNoSuchElementException

java.util.NoSuchElementException

スレッドで

例外「メイン」それは何を意味し、どのように私はそれを動作させるには、問題を解決するだろうか?

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!"); 

      } 
     } 
    } 
} 
+0

スキャナを閉じないでください。それは 'System.in'ストリームを閉じます。 – ifly6

答えて

-1

あなたが持っている問題は、スキャナを閉じているために例外が発生していることです。これを試してみてください:

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(); 

    } 

私はコードにあるように1つのスキャナだけを使用することをお勧めします。

+0

'System.in'を閉じる必要はありません。実際にはリソースリークではありません。 – ifly6

+0

乾杯!入力とアドバイスをありがとう! (プログラミングの初心者) – solorzke

関連する問題