how to catch blank input with scanner class in jav

2019-05-05 11:02发布

问题:

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();
        }
    }

回答1:

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.



回答2:

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...