java.util.NoSuchElementException:在java.util.Scanner.nextLine中找不到行(Scanner.java:1585)

时间:2013-07-03 22:20:29

标签: java exception java.util.scanner

我一次又一次地提示用户输入,直到用户键入exit,在这种情况下数据对象将被设置为null并且它将离开循环。在大多数情况下,此代码可以正常工作,但有时我会在行上发现 NoSuchElementException reader = new Scanner(System.in);。这往往发生在几个循环后,而不是第一次通过。如果我在while循环的范围内声明读者变量,那么它将在第二个循环中失败。

大部分工作(有时抛出异常)

int level = 1;  
Scanner reader;
String selection = null;

while (true) {
    if (data.done) {
        level--;
    }

    data.done = false;
    System.out.println(getSubmenu(level, data));

    reader = new Scanner(System.in);

    if (level <6) {
        selection = reader.nextLine();
    } else {
        level = 4;
    }

    if (validSelection(selection)) {
        level = getLevel(level, selection);
        data = getData(level, data, selection);
    } else {
        System.out.println("Invalid entry");
    }

    if (data == null) {
        System.out.println("Level "+ level + "selection " + selection);
        break; // exit command was typed
    }
}
reader.close();

Alternate(在第二次循环时抛出异常)

int level = 1;  
String selection = null;

while (true) {
    if (data.done) {
        level--;
    }

    data.done = false;
    System.out.println(getSubmenu(level, data));

    Scanner reader = new Scanner(System.in);

    if (level <6) {
        selection = reader.nextLine();
    } else {
        level = 4;
    }

    if (validSelection(selection)) {
        level = getLevel(level, selection);
        data = getData(level, data, selection);
    } else {
        System.out.println("Invalid entry");
    }

    if (data == null) {
        System.out.println("Level "+ level + "selection " + selection);
        break; // exit command was typed
    }
    reader.close();
}

栈跟踪

java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Scanner.java:1585)
at org.functional.utils.Menu.run(ServerScripts.java:61)
at org.functional.utils.ServerScripts.main(ServerScripts.java:18)

我错过了什么?

1 个答案:

答案 0 :(得分:7)

在代码的开头分配Scanner,而不是每次都在循环中分配:

int level = 1;  
Scanner reader = new Scanner(System.in);
String selection = null;

while (true) {
    if (data.done) {
        level--;
    }

    data.done = false;
    System.out.println(getSubmenu(level, data));

    if (level <6) {
        selection = reader.nextLine();
    } else {
        level = 4;
    }

    if (validSelection(selection)) {
        level = getLevel(level, selection);
        data = getData(level, data, selection);
    } else {
        System.out.println("Invalid entry");
    }

    if (data == null) {
        System.out.println("Level "+ level + "selection " + selection);
        break; // exit command was typed
    }
}
reader.close();

您执行此操作的方式,您创建的每个Scanner都会在下一次循环迭代时保持孤立状态。他们都没有被关闭。当从所有垃圾Scanner对象中消耗一些内部资源时,很可能会出现异常。