Search code examples
javainputuser-input

Meaning of input.nextLine()


I am taking a course on Java and the "instructor" is introducing how to get the user's input. I don't understand what is the "input.nextLine()" for.

Here's the code:

import java.util.Scanner;

public class Application {
    public static void main(String[] args) {

        // Create Scanner object
        Scanner input = new Scanner(System.in);

        // Output the prompt
        System.out.println("Type in something: ");

        // Wait for the user to enter a line of text
        String line = input.nextLine();

        // Tell them what they entered
        System.out.println("You just typed " + "'" + line + "'.");
    }
}

Solution

  • It is for reading the next line from the input stream.

    Scanner input = new Scanner(System.in); 
    // create a new reference and refer to the input stream.
    String line = input.nextLine(); 
    // read the next line from the stream (entered from the keyboard) and store it in a String variable named line