2016-10-17 4 views
-2

Im은 while 루프 내에서 모든 사용자의 입력 응답을 읽어 해당 연도가 윤년인지 여부를 확인하는 프로그램입니다. 스레드 "주요"java.util.NoSuchElementException이 무슨 뜻이며 어떻게 그것을 실행하려면 문제를 해결할 수있는 어떤Scanner와 System.in을 사용하는 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(); 

    } 

코드에있는 것처럼 하나의 스캐너 만 사용하는 것이 좋습니다.

+0

당신은'System.in'을 닫을 필요가 없습니다. 실제로는 리소스 누출이 아닙니다. – ifly6

+0

건배! 의견을 보내 주셔서 감사합니다! (프로그래밍 처음 습득) – solorzke