I am having trouble trying to use the nextLine () method from java.util.Scanner.
Here is what I tried:
import java.util.Scanner; class TestRevised { 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); } }
Example # 1: This example works as intended. String String sentence = scanner.nextLine(); waits for input before continuing System.out.print("Enter an index:\t"); .
This leads to the output:
Enter a sentence: Hello. Enter an index: 0 Your sentence: Hello. Your index: 0
// Example
Example # 2: This example does not work properly. This example uses a while and if - else loop to let the user choose what to do. As soon as the program reaches String sentence = scanner.nextLine(); , it does not wait for input, but instead executes the line System.out.print("Enter an index:\t"); .
This leads to the output:
Menu Options (1) - do this (2) - quit Please enter your selection: 1 Enter a sentence: Enter an index:
This makes it impossible to enter a sentence.
Why does example # 2 not work as intended? The only difference between Ex. 1 and 2 are an example. 2 has a while loop and an if-else structure. I do not understand why this affects the behavior of the .nextInt () scanner.
java java.util.scanner
Taylor P. Feb 17 2018-11-17T00: 00Z
source share