Home >Java >javaTutorial >Why Does `nextLine()` Misbehave After `nextInt()` and How Can It Be Fixed?

Why Does `nextLine()` Misbehave After `nextInt()` and How Can It Be Fixed?

Barbara Streisand
Barbara StreisandOriginal
2024-12-14 13:30:11456browse

Why Does `nextLine()` Misbehave After `nextInt()` and How Can It Be Fixed?

Correcting nextLine() Behavior

The issue encountered when using nextLine() in the second code example stems from the combination of nextInt() and nextLine().

The Problem with nextInt()

nextLine() consumes the entire line, including whitespace and characters entered before pressing the Enter key. However, nextInt() only consumes the numeric value. If non-numeric characters or whitespace follow the number, nextLine() will attempt to read them, resulting in unexpected behavior.

Solution: Consume Remaining Newline

To ensure that nextLine() reads the complete line as intended, you can add a nextLine() call after each nextInt() to consume any residual characters on the line. This ensures that when nextLine() is used to read the sentence, it will receive a complete line.

Example with Corrections:

// Example #2 (Corrected)
import java.util.Scanner;

class Test {
    public void menu() {
        Scanner scanner = new Scanner(System.in);

        while (true) {
            System.out.println("\nMenu Options\n");
            System.out.println("(1) - do this");
            System.out.println("(2) - quit");

            System.out.print("Please enter your selection:\t");
            int selection = scanner.nextInt();
            scanner.nextLine(); // Consume remaining newline

            if (selection == 1) {
                System.out.print("Enter a sentence:\t");
                String sentence = scanner.nextLine();

                System.out.print("Enter an index:\t");
                int index = scanner.nextInt();

                System.out.println("\nYour sentence:\t" + sentence);
                System.out.println("Your index:\t" + index);
            }
            else if (selection == 2) {
                break;
            }
        }
    }
}

The above is the detailed content of Why Does `nextLine()` Misbehave After `nextInt()` and How Can It Be Fixed?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn