Java Wait for Input

Siddharth Swami May 29, 2021
Java Wait for Input

User input may refer to any information or data that a user wants the compiler to process. We might encounter situations where we want our program to pause compilation and wait for the user to input some value.

For such situations, we can use the nextLine() function.

In this tutorial, we will learn how to get Java to wait for user input using the nextLine() method.

The nextLine() function is found in the java.util.Scanner class in Java. This function is used to move past the current line and return some input.

So by using this method, the compiler waits for the user to input a valid string and resume compilation of the program. This method is only applicable to string datatype.

For example,

// Java program to illustrate the
// nextLine() method of Scanner class in Java
  
import java.util.Scanner;
  
public class Scanner_Class {
    public static void main(String[] args)
    {
        // create a new scanner
        // with the specified String Object
        Scanner scanner = new Scanner(System.in);
        String s= scanner.nextLine();
        // print the next line
        System.out.println("The line entered by the user: "+s);
        scanner.close();
    }
}

Input:

Hello World.

Output:

The line entered by the user: Hello World.

There is no need to wait to check the availability of input as the Scanner.nextLine() will automatically block until a line is available.

The following code explains this.

import java.util.Scanner;
public class Scanner_Test {

    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");
        }
    }
}

Output:

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

In the above example, we calculated and showed the time the compiler waited for the input using the currentTimeMillis() function.

This function may return two exceptions. The IllegalStateException is raised when the Scanner is closed, and the NoSuchElementException is raised when no line is found.

Related Article - Java Input