Config Router

  • Google Sheets
  • CCNA Online training
    • CCNA
  • CISCO Lab Guides
    • CCNA Security Lab Manual With Solutions
    • CCNP Route Lab Manual with Solutions
    • CCNP Switch Lab Manual with Solutions
  • Juniper
  • Linux
  • DevOps Tutorials
  • Python Array
You are here: Home / How to get Java to wait for user Input

How to get Java to wait for user Input

August 20, 2021 by James Palmer

There is no need for you to check for available input waiting and sleeping until there is since Scanner.nextLine() will block until a line is available.
Have a look at this 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”);
}
}
}

Please input a line
hello
Waited 1.892s for user input
User input was: hello
Please input a line
^D
System.in was closed; exiting

So all you have to do is to use Scanner.nextLine() and your app will wait until the user has entered a newline. You also don’t want to define your Scanner inside the loop and close it since you’re going to 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
}
}
}

Related

Filed Under: Uncategorized

Recent Posts

  • How do I give user access to Jenkins?
  • What is docker volume command?
  • What is the date format in Unix?
  • What is the difference between ARG and ENV Docker?
  • What is rsync command Linux?
  • How to Add Music to Snapchat 2021 Android? | How to Search, Add, Share Songs on Snapchat Story?
  • How to Enable Snapchat Notifications for Android & iPhone? | Steps to Turn on Snapchat Bitmoji Notification
  • Easy Methods to Fix Snapchat Camera Not Working Black Screen Issue | Reasons & Troubleshooting Tips to Solve Snapchat Camera Problems
  • Detailed Procedure for How to Update Snapchat on iOS 14 for Free
  • What is Snapchat Spotlight Feature? How to Make a Spotlight on Snapchat?
  • Snapchat Hack Tutorial 2021: Can I hack a Snapchat Account without them knowing?

Copyright © 2025 · News Pro Theme on Genesis Framework · WordPress · Log in