Reputation: 17869
I have a scanner asking for some preferences. It creates an int
variable choice
between 0 and 3. Then I do the following:
String location;
switch(choice){
case 0:
System.out.println("Please type the zip codes you would like to search in a comma separated list");
location = input.nextLine();
break;
case 1:
System.out.println("Please type the street names you would like to search in a comma separated list");
location = input.nextLine().toUpperCase();
break;
case 2:
System.out.println("Please type the boroughs you would like to search in a comma separated list");
location = input.nextLine().toUpperCase();
break;
default:
location = "none";
break;
}
String locations[] = location.split("\\s*,\\s*");
now to me this seems perfectly fine, but when choice is set to 0,1, or 2 it will print the correct line, but skip the part where the user has to input something (the line that looks like location=...)
this means that it does not give the user the chance to enter anything and therefore locations
becomes a blank list. Why does this happen and how can I fix it?
Upvotes: 1
Views: 3277
Reputation: 1
Put nextLine after the read before the switch.
System.out.print("Digite um número ente 1 e 9: ");
int opc = read.nextInt();
read.nextLine();
switch(opc) {
And read your value with nextLine()
case 6:
String[] procurados = read.nextLine().split(" ");
Upvotes: 0
Reputation: 1
I faced the same problem as you. Try:
case 'f' :
System.out.println("Enter a word or phrase to be found:");
scnr.nextLine();
String phrase = scnr.nextLine(); //
Upvotes: 0
Reputation: 68887
You are probably reading the newline after the last input, instead of the really next line. Try:
int choice = input.nextInt();
input.nextLine(); // <--- Eat it here!
String location;
switch(choice){
case 0:
Syst...
The nextInt()
call, where you prompt the choice, does not end the line. So the first call to nextLine()
after nextInt()
is going to return an empty String. To fix that, eat the empty line after the integer and then move on.
Upvotes: 5