Using scanner.nextLine()
In Java, the nextLine() method from the java.util.Scanner class reads a single line of text from a stream. It is commonly used to read input from the user.
Consider the following examples:
Example 1: Reading a Single Line
import java.util.Scanner; class Test { public void menu() { Scanner scanner = new Scanner(System.in); 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); } }
In this example, the nextLine() method reads the user's input for the sentence. It properly waits for the user to enter a value before continuing to read the index.
Example 2: Reading in a Loop
// Example 2 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(); 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; } else { System.out.print("Invalid input. Please try again: "); scanner.nextLine(); } } } }
In this example, the issue where the nextLine() method does not read input in the loop is resolved by explicitly calling scanner.nextLine() after reading the selection integer. This ensures that any remaining characters in the input buffer are discarded, allowing the nextLine() call for the sentence to work correctly.
The above is the detailed content of How Does Java's `scanner.nextLine()` Handle Input, Especially in Loops?. For more information, please follow other related articles on the PHP Chinese website!