how to catch blank input with scanner class in java

断了今生、忘了曾经 提交于 2019-12-05 13:22:10

Scanner is a "for dummies" implementation of file I/O for input. It allows tutorial and textbook writers to write demo code without moaning about the complications of it.

If you really want to know what you're reading, you have to say something like

BufferedReader br = new BufferedReader(new FileReader("myfile.txt"))

...and then you can do

String line = br.readLine()

and see nothing but the truth.

select = br.next();

... blocks until it finds a suitable token. This means it will wait until it sees a token to return, therefore you won't get a blank line back from it.

Try substituting these lines:

//select = br.next();    // old version with Scanner

BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
try {
  select = bufferedReader.readLine();
} catch (IOException e) {
  throw new RuntimeException(e);
}
System.out.println(">" + select + "<"); // should be able to see empty lines now...
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!