java中scanner输入,如何在java中使用scanner类捕获空白输入

I am using the scanner class to capture user input from the command line (strings only), as an alternative to my previous question.

The following seems to work fine, except the blank lines are not caught as they should by the second conditional. For example when I press enter, this should be captured as a blank line and the second conditional should be true. However a new blank line is displayed on the console everytime, with the entire console "scrolling" upward if I keep hitting enter, rather than the logic in the conditional.

Is there a proper way to catch a blank input from the command line using scanner? (someone hitting just enter, or hit space a few times and then enter)

Thank you for any advice

Machine aMachine = new Machine();

String select;

Scanner br = new Scanner(System.in);

while(aMachine.stillInUse()){

select = br.next();

if (Pattern.matches("[rqRQ1-6]", select.trim())) {

aMachine.getCommand(select.trim().toUpperCase()).execute(aMachine);

}

/*

* Ignore blank input lines and simply

* redisplay current status -- Scanner doesn't catch this

*/

else if(select.trim().isEmpty()){

aMachine.getStatus();

/*

* Everything else is treated

* as an invalid command

*/

else {

System.out.println(aMachine.badCommand()+select);

aMachine.getStatus();

}

}

解决方案

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值