如何使用Java Scanner测试空白行?

我希望用扫描仪输入,直到没有任何东西(即当用户输入空行时)。 我该如何实现这一目标?

我试过了:

while (scanner.hasNext()) { // process input } 

但那会让我陷入困境

这是一种方式:

 Scanner keyboard = new Scanner(System.in); String line = null; while(!(line = keyboard.nextLine()).isEmpty()) { String[] values = line.split("\\s+"); System.out.print("entered: " + Arrays.toString(values) + "\n"); } System.out.print("Bye!"); 

来自http://www.java-made-easy.com/java-scanner-help.html :

问:如果我使用Java扫描仪扫描空行会怎样?

答:这取决于。 如果您正在使用nextLine(),则会将空行读入为空字符串。 这意味着如果要将空行存储在String变量中,则变量将保持为“”。 它不会存储“”或者放置了许多空格。 如果您正在使用next(),那么它根本不会读取空白行。 它们完全被跳过了。

我的猜测是nextLine()仍会在一个空白行上触发,因为从技术上讲,Scanner将有空字符串"" 。 所以,你可以检查if s.nextLine().equals("")

使用scanner.nextLine()的建议的问题是它实际上将下一行作为String返回。 这意味着任何文本都会消耗掉。 如果你有兴趣扫描那条线的内容……好吧,太糟糕了! 您必须自己解析返回的String的内容。

更好的方法是使用

 while (scanner.findInLine("(?=\\S)") != null) { // Process the line here… … // After processing this line, advance to the next line (unless at EOF) if (scanner.hasNextLine()) { scanner.nextLine(); } else { break; } } 

由于(?=\S)是零宽度前瞻断言,因此它永远不会消耗任何输入。 如果它在当前行中找到任何非空白文本,它将执行循环体。

你可以省略else break; 如果您确定循环体已经消耗了该行中的所有非空白文本。

AlexFZ是对的,scanner.hasNext scanner.hasNext()将始终为true且循环不会结束,因为即使它是空的“”也总是有字符串输入。

我遇到了同样的问题,我解决了这个问题:

 do{ // process input 
}while(line.length()!=0);

我认为do-while更适合这里,因为你必须在用户输入后评估输入。

 Scanner key = new Scanner(new File("data.txt")); String data = ""; while(key.hasNextLine()){ String nextLine = key.nextLine(); data += nextLine.equals("") ? "\n" :nextLine; } System.out.println(data);