本文介绍了在java.util.Scanner.throwFor(未知来源)错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  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;

        }

所以第二次调用此方法时返回以下内容错误。

So the second time I call this method its returning the following error.

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(); 哪个运行正常,然后secondis height = posNum(); 这不允许在输入错误之前输入值。

The first call is rad = posNum(); which runs fine and then secondis height = posNum(); which doesn't allow a value to be entered before it goes to the error.

谢谢

推荐答案

同时拨打下一步你应该检查扫描仪是否有一个。

while calling next you should check if scanner has one.

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

根据

您可以更改下面的方法

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);

这篇关于在java.util.Scanner.throwFor(未知来源)错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-28 07:18