mercredi 21 octobre 2015

Trying to use scanner in java to read just a stroke of the return key as an input?

I am making a program that will read user input and determine with an if else loop what to do. If the user hits just enter and doesn't type anything else in, I want to loop something through the if. If anything else is typed as an input, the program should exit back to a different menu. Here is what I have so far:

Scanner scnr = new Scanner(System.in);
String choice;
choice = scnr.next();
if (choice.equals("")){ ...
}
else {...
}

When I run through it, just pressing enter does affect anything, it just makes advances to the next line in the console. However, when I type something in, the error part that sends it to the menu when anything else is typed in works just fine. I'm thinking I have to use something besides scnr.next(); but I don't know what that would be.

This is for an entry level class, and it requires that we use the scanner utility and not something more advanced. Thanks in advance.

Aucun commentaire:

Enregistrer un commentaire