java - 使用 next() 时扫描仪中出现 NoSuchElementException

标签 java java.util.scanner

我基本上是在尝试填充 String[][]。 每当我使用扫描仪的 next() 函数时,它都会抛出异常。

你能帮忙吗?

public static void main(String[] args) throws NumberFormatException, Exception {

    int k,i;
    int n = Integer.parseInt(IO.promptAndRead("Bitte geben Sie eine Zahl zwischen 5 und 50 ein: ")); // any number between 5 and 50
    String name= IO.promptAndRead("Bitte geben Sie Ihren Vor- und Zunamen ein: "); //for example "Hans Zimmermann"
    n=n-1;
    String[][] matrix = new String[n][n];

    Scanner sc = new Scanner(name);

    boolean b_switch = false;

    for (i = 0; i<n;i++) {
        b_switch = !b_switch;
        if (b_switch == true) {
            for (k = 0; k<n;k++) {
                matrix[i][k] = sc.next();
            }
            if (i+1 < n){
                matrix[i+1][k] = sc.next();
            }
        }
        else {
            for (k = n; k>0;k--) {
                matrix[i][k] = sc.next();
            }

            if (i+1 < n){
                matrix[i+1][k] = sc.next();
            }
        }
    }

我的控制台输出:

Bitte geben Sie eine Zahl zwischen 5 und 50 ein: 15
Bitte geben Sie Ihren Vor- und Zunamen ein: asdf
    Exception in thread "main" java.util.NoSuchElementException
        at java.util.Scanner.throwFor(Unknown Source)
        at java.util.Scanner.next(Unknown Source)
        at ep1_uebung6.Maender.main(Maender.java:25)

最佳答案

您收到 NoSuchElementException,因为您在代码中使用 sc.next() 而不验证是否存在任何元素。

您应该在调用 sc.next() 之前检查是否存在,如下所示。

if (sc.hasNext()) {
    matrix[i][k] = sc.next();
}

For more information, refer the JavaDoc.

关于java - 使用 next() 时扫描仪中出现 NoSuchElementException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27004342/

相关文章:

java - Ant 脚本从多个模块运行单元测试,如果测试失败则构建失败

java - 数组列表的元素作为文件行中的替换

用于测试类的 Java Bean

java - 扫描仪在使用 next() 或 nextFoo() 后跳过 nextLine()?

java - 扫描仪在使用 next() 或 nextFoo() 后跳过 nextLine()?

Java Scanner 打印上一行和下一行

java - 我可以使用什么方法通过 Java 配置/更新弹性负载均衡器?

java - 默认异常处理程序显式处理异常的首选方法是什么?

java - 使用 Java SimpleDateFormat 查找最大日期

Java maven 项目 - 从主类运行时有效,但从 'fat' jar 运行时无效