2
  private static int posNum() {
            Scanner scan = new Scanner(System.in);
            int input = 0;
            boolean error;

            if (scan.hasNextInt()) {
                input = scan.nextInt();
                error = input <= 0;
            } else {
    28          scan.next();
                error = true;
            }
            while (error) {
                System.out.print("Invalid input. Please reenter: ");
                if (scan.hasNextInt()) {
                    input = scan.nextInt();
                    error = input <= 0;
                } else {
                    scan.next();
                    error = true;
                }
            }
            scan.close();
            return input;

        }

所以我第二次调用这个方法它返回以下错误。

Exception in thread "main" java.util.NoSuchElementException
    at java.util.Scanner.throwFor(Unknown Source)
    at java.util.Scanner.next(Unknown Source)
    at q2.CylinderStats.posNum(CylinderStats.java:28)
    at q2.CylinderStats.main(CylinderStats.java:62)

第一次调用rad = posNum();运行良好,然后第二次调用height = posNum();在出错之前不允许输入值。

谢谢

4

2 回答 2

2

打电话时next你应该检查扫描仪是否有一个。

 if(scan.hasNext())
 scan.next();

根据Scanner#next的 java doc

NoSuchElementException 如果没有更多可用的令牌

你可以改变你的方法如下

private static int posNum(Scanner scan) {
    int input = 0;
    boolean error = false;
    if (scan.hasNext()) {
        if (scan.hasNextInt()) {
            input = scan.nextInt();
            error = input <= 0;
        } else {
            scan.next();
            error = true;
        }
    }
    while (error) {
        System.out.print("Invalid input. Please reenter: ");
        if (scan.hasNextInt()) {
            input = scan.nextInt();
            error = input <= 0;
        } else {
            if (scan.hasNext())
                scan.next();
            error = true;
        }
    }
    return input;
}

然后像下面这样调用它

    Scanner scan = new Scanner(System.in);
    int i = posNum(scan);
    System.out.println(i);
    int j = posNum(scan);
    System.out.println(j);
于 2012-10-13T16:02:35.513 回答
2

它运行一次并给您带来麻烦的事实意味着它无法从流中读取任何内容。

来自 Java 文档:

当 Scanner 关闭时,如果源实现了 Closeable 接口,它将关闭其输入源。

这意味着它关闭了 System.in

So leaving the scanner opened will prevent the error the second time.

Remove scan.close(); and your program should work fine!

于 2014-04-09T15:10:11.653 回答