2

我一遍又一遍地提示用户输入,直到用户类型退出,在这种情况下,数据对象将被设置为 null 并且它将离开循环。在大多数情况下,此代码有效,但有时我会在行上得到NoSuchElementExceptionreader = new Scanner(System.in); : 。这往往发生在几个循环之后,而不是第一次。如果我在 while 循环的范围内另外声明 reader 变量,那么它将在第二个循环中失败。

主要工作(有时抛出异常)

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

备用(在第二个循环中抛出异常)

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)

我错过了什么?

4

1 回答 1

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当从所有这些垃圾对象中消耗一些内部资源时,最有可能出现异常。

于 2013-07-03T22:28:06.193 回答