Scanner nextLine() Method Example

1. Introduction

The Scanner class in Java is a simple text scanner that can parse primitive types and strings using regular expressions. It breaks its input into tokens using a delimiter pattern, which by default matches whitespace. The nextLine() method is particularly useful when you must capture an entire line of input, including spaces, which is impossible with methods like next() that only read input until the space.

2. Program Steps

1. Import the Scanner class.

2. Create a new Scanner instance to read from System.in.

3. Prompt the user to enter a line of text.

4. Use the nextLine() method to read the entire line of text.

5. Close the scanner to prevent resource leaks.

3. Code Program

import java.util.Scanner;

public class ScannerNextLineExample {
    public static void main(String[] args) {
        // Step 1: Creating a Scanner object to read input from standard input stream
        Scanner scanner = new Scanner(System.in);

        // Step 2: Prompting the user to enter a line of text
        System.out.println("Enter a line of text:");

        // Step 3: Reading the entire line of text entered by the user
        String line = scanner.nextLine();

        // Step 4: Displaying the line of text entered by the user
        System.out.println("You entered: " + line);

        // Step 5: Closing the scanner
        scanner.close();
    }
}

Output:

(Example output based on user input "Hello, this is a test.")
Enter a line of text:
You entered: Hello, this is a test.

Explanation:

1. A Scanner object named scanner is created to read text from the System.in input stream, allowing the program to read input provided by the user through the console.

2. The user is prompted to enter a line of text. This instruction is displayed on the console using System.out.println.

3. The nextLine() method is called on the scanner object to read an entire line of input from the user. Unlike next(), nextLine() captures everything up to the end of the line, including spaces.

4. The text entered by the user is then printed to the console, showing the use of nextLine() for capturing and echoing full lines of input.

5. Finally, the scanner is closed using the close() method to prevent resource leaks. It's a good practice to close the Scanner object when it's no longer needed.

Comments