How to catch empty input with class scanner in java

I am using a scanner class to enter user input from the command line (string only) as an alternative to the previous question .

Everything seems to be working fine, except that empty lines are not caught, just like the second condition. For example, when I press enter, this should be written as an empty string, and the second condition should be true. However, a new empty line is displayed on the console every time, while the entire console "scrolls" up if I continue to enter enter, and not in the conditional logic.

Is there a correct way to catch empty input from the command line using a scanner? (someone hit, just type or press spacebar several times and then enter)

Thanks 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();
        }
    }
+4
2

Scanner - "-" - " ". -, .

, , -

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

...

String line = br.readLine()

, .

+1

select = br.next();

... , . , , , , .

:

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

All Articles