2013-07-26 2 views
1

양수 int를 요청하고 사용자로부터 양수 int가 수신 될 때까지 충돌이나 닫히지 않는 간단한 프로그램을 만들려고합니다. 그러나 내 프로그램은 계속 충돌하고 NoSuchElementException 오류를보고합니다. 스캐너가 두 번 이상있는 메서드를 호출하면 오류가 발생합니다. 나는이 프로그램의 기초를 사용하여 내가하고있는 다른 일들을 도울 것이다. 다음은 현재 코드입니다.Scanner throwing NoSuchElementException

import java.util.InputMismatchException; 
import java.util.Scanner; 

public class test2 { 

/** 
* Test ways to avoid crashes when entering integers 
*/ 
public static void main(String[] args) { 
    int num = testnum(); 
    System.out.println("Thanks for the " + num + "."); 
} 

public static int testnum() { 
    int x = 0; 
    System.out.println("Please enter a positivie integer;"); 
    x = getnum(); 
    while (x <= 0) { 
     System.out.println("That was not a positive integer, please enter a positive integer;"); 
     x = getnum(); 
    } 
    return x; 
} 

public static int getnum() { 
    Scanner scan = new Scanner(System.in); 
    int testint; 
    try { 
     testint = scan.nextInt(); 
    } catch (InputMismatchException e) { 
     scan.close(); 
     return 0; 
    } 
    scan.close(); 
    return testint; 
} 
} 

어떤 도움을 크게 감상 할 수있다, 감사합니다 :)

답변

0

getnum() 방법에 스캐너를 닫지 마십시오.

public static int getnum() { 
    Scanner scan = new Scanner(System.in); 
    int testint; 
    try { 
     testint = scan.nextInt(); 
    } catch (InputMismatchException e) { 
     scan.close(); 
     return 0; 
    } 
// scan.close(); 
    return testint; 
} 
+5

또는 더 나은 방법으로 전체 응용 프로그램 수명 동안 단일 '스캐너'를 사용하고 응용 프로그램을 마치려고 할 때만 닫습니다. –

+0

예. 그게 나아. – Masudul

+0

@MasudCSECUET 만약 거기에 그것을 닫지 않으면 이클립스는 내가 리소스 누수가 있다고 알려주지 만 그것을 무시해야합니까? – Julian

1

이 클래스를 사용해보세요. 코드의 주석은 모두 설명합니다.

import java.util.Scanner; 

public class GetPositiveInteger { 

    private static Scanner scan = new Scanner(System.in); //scanner variable accessible by the entire class 

    /* 
    * main method, starting point 
    */ 
    public static void main(String[] args) { 
     int num = 0; //create an integer 
     while(num <= 0) //while the integer is less than or equal to 0 
      num = getPostiveNumber(); //get a new integer 
     System.out.println("Thanks for the number, " + num); //print it out 
    } 
    public static int getPostiveNumber() { //method to get a new integer 
     System.out.print("Enter a postive number: "); //prompt 
     try { 
      return scan.nextInt(); //get the integer 
     } catch (Exception err) { 
      return 0; //if it isn't an integer, try again 
     } 
    } 
} 
관련 문제