扫描仪抛出NoSuchElementException

时间:2013-07-26 05:48:18

标签: java int java.util.scanner nosuchelementexception

我正在尝试创建一个简单的小程序,它将要求一个正整数,并且在它从用户收到一个正int之前不会崩溃或关闭。但是,当我的程序多次调用带有Scanner的方法时,我的程序会一直崩溃并报告错误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;
}
}

非常感谢任何帮助,谢谢:)

2 个答案:

答案 0 :(得分:1)

请勿以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;
}

答案 1 :(得分: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
        }
    }
}