Monday, 14 November 2016

java - Using scanner.nextLine()





I have been having trouble while attempting 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. The line String sentence = scanner.nextLine(); waits for input to be entered before continuing on to System.out.print("Enter an index:\t");.



This produces the output:




Enter a sentence:   Hello.
Enter an index: 0

Your sentence: Hello.
Your index: 0





// 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;
}
}
}
}



Example #2: This example does not work as intended. This example uses a while loop and and if - else structure to allow the user to choose what to do. Once the program gets to String sentence = scanner.nextLine();, it does not wait for input but instead executes the line System.out.print("Enter an index:\t");.



This produces the output:



Menu Options

(1) - do this
(2) - quit


Please enter your selection: 1
Enter a sentence: Enter an index:


Which makes it impossible to enter a sentence.






Why does example #2 not work as intended? The only difference between Ex. 1 and 2 is that Ex. 2 has a while loop and an if-else structure. I don't understand why this affects the behavior of scanner.nextInt().



Answer



I think your problem is that



int selection = scanner.nextInt();


reads just the number, not the end of line or anything after the number. When you declare



String sentence = scanner.nextLine();



This reads the remainder of the line with the number on it (with nothing after the number I suspect)



Try placing a scanner.nextLine(); after each nextInt() if you intend to ignore the rest of the line.


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...