양수 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;
}
}
어떤 도움을 크게 감상 할 수있다, 감사합니다 :)
또는 더 나은 방법으로 전체 응용 프로그램 수명 동안 단일 '스캐너'를 사용하고 응용 프로그램을 마치려고 할 때만 닫습니다. –
예. 그게 나아. – Masudul
@MasudCSECUET 만약 거기에 그것을 닫지 않으면 이클립스는 내가 리소스 누수가 있다고 알려주지 만 그것을 무시해야합니까? – Julian