I have a basic console app where I'm just trying to use a simple Scanner in a while loop to catch user input. I've tried putting standardInput = System.in
in the build.gradle
, but my program doesn't block when it should to wait for input.
while (stillWriting) {
System.out.println(
"Press 1 to write something,\n" +
"Press 2 to erase something,\n" +
"Press 3 to exit."
);
//if you select 1, it goes into the case, but does not block
//then ends up here again.
int userSelection = scanner.nextInt();
switch (userSelection) {
case 1:
System.out.println("Enter text to be written: ");
//vvvvvv should block here but doesn't. vvvvvv
String textToWrite = scanner.nextLine();
paper = pencil.write(paper, textToWrite);
break;
case 2:
//some code
break;
case 3:
stillWriting = false;
break;
default:
System.out.println(userSelection + " is not valid.");
break;
}
}
Are there any alternatives or jars I can use that make it block correctly and actually wait for input?
turns out in each case that you want to take input, if you just reassign a new Scanner() to the scanner variable, it will correctly block.
Still won't pick up a newline character though.
You have to consume the <Enter>
that the user inputs to make his choice, otherwise it would (instantly) be consumed by your String textToWrite = scanner.nextLine();
:
[...]
int userSelection = scanner.nextInt();
scanner.nextLine(); // <-- consume the <enter>
switch (userSelection) {
[...]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.