0

I have a while loop which detects if sc.hasNext() is true and takes in the list of inputs typed, adding it to the list textEditor one by one.

         while (sc.hasNext()) {
            String line = sc.nextLine();
            if (!(line.isEmpty())){
                textEditor.addString(line);
            }
        }
        sc.close();
        textEditor.printAll();
    }
}

However, when I type in a list of strings e.g.

oneword
two words
Hello World
hello World

the loop does not stop and the method printAll() is not called. How do I break out of the while loop?

4

2 回答 2

0

您可以使用 break 语句跳出循环:

    while (sc.hasNextLine()) {
        String line = sc.nextLine();
        if (!(line.isEmpty())){
            textEditor.addString(line);
        } else {
            break;
        }
    }
    textEditor.printAll();

(顺便说一句,不要关闭标准输出、标准错误或标准输入,即在 Java 中:System.out、System.err 和 System.in)

于 2019-02-21T16:22:26.317 回答
0

语句中没有breakwhile所以你进入无限循环。

我用一个简单的System.out.println. 看一下新的while条件,当接收到一个空字符串时它会退出while语句:

Scanner sc = new Scanner(System.in);
String line;
while (!(line = sc.nextLine()).isEmpty()) {
    System.out.println("Received line : " + line);
    //textEditor.addString(line);
}
sc.close();

System.out.println("The end");
于 2019-02-21T16:29:12.813 回答