在接受所有输入后如何摆脱while循环?

问题描述 投票:1回答:2

我有一个while循环,它检测sc.hasNext()是否为true并接受输入的输入列表,将其逐个添加到列表textEditor中。

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

但是,当我输入字符串列表时,例如

oneword
two words
Hello World
hello World

循环不会停止,并且不会调用printAll()方法。如何突破while循环?

java while-loop infinite
2个回答
1
投票

break语句中没有while,所以你进入无限循环。

我用简单的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");

0
投票

您可以使用break语句中断循环:

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

(顺便说一句,不要关闭stdout,stderr或stdin,即Java:System.out,System.err和System.in)

© www.soinside.com 2019 - 2024. All rights reserved.