How to make Java wait for user input
•
Java
I'm trying to make an IRC robot for my channel I hope the robot can get commands from the console In order to make the main loop wait for the user to enter something I added to the loop:
while(!userInput.hasNext());
It doesn't seem to work I've heard of BufferedReader, but I've never used it, and I'm not sure if it will solve my problem
while(true) {
System.out.println("Ready for a new command sir.");
Scanner userInput = new Scanner(system.in);
while(!userInput.hasNext());
String input = "";
if (userInput.hasNext()) input = userInput.nextLine();
System.out.println("input is '" + input + "'");
if (!input.equals("")) {
//main code
}
userInput.close();
Thread.sleep(1000);
}
Solution
You do not need to check for available input, wait and Hibernate until scanner Nextline() will block until a line is available
Take a look at the example I wrote to demonstrate it:
public class ScannerTest {
public static void main(String[] args) {
Scanner scanner = new Scanner(system.in);
try {
while (true) {
System.out.println("Please input a line");
long then = System.currentTimeMillis();
String line = scanner.nextLine();
long Now = System.currentTimeMillis();
System.out.printf("Waited %.3fs for user input%n",(Now - then) / 1000d);
System.out.printf("User input was: %s%n",line);
}
} catch(IllegalStateException | NoSuchElementException e) {
// system.in has been closed
System.out.println("system.in was closed; exiting");
}
}
}
Therefore, all you have to do is use scanner Nextline(), your application will wait until the user enters a newline character You also don't want to define your scanner in the loop and turn it off, because you will use it again in the next iteration:
Scanner userInput = new Scanner(system.in);
while(true) {
System.out.println("Ready for a new command sir.");
String input = userInput.nextLine();
System.out.println("input is '" + input + "'");
if (!input.isEmpty()) {
// Handle input
}
}
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码
