如何使用Java Scanner测试空白行? [英] How to test for blank line with Java Scanner?

查看:449
本文介绍了如何使用Java Scanner测试空白行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am expecting input with the scanner until there is nothing (i.e. when user enters a blank line). How do I achieve this?

我试过:

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

但这会让我陷入困境循环

But that will get me stuck in the loop

推荐答案

这是一种方式:

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!");

这篇关于如何使用Java Scanner测试空白行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆