Rya*_*axe 1 java input switch-statement java.util.scanner
我有一台扫描仪,询问一些偏好。它创建一个介于 0 和 3 之间的int变量choice。然后我执行以下操作:
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*");
Run Code Online (Sandbox Code Playgroud)
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=...)
这意味着它不会给用户输入任何内容的机会,因此locations变成了一个空白列表。为什么会发生这种情况,我该如何解决?
您可能正在阅读最后一个输入之后的换行符,而不是真正的下一行。尝试:
int choice = input.nextInt();
input.nextLine(); // <--- Eat it here!
String location;
switch(choice){
case 0:
Syst...
Run Code Online (Sandbox Code Playgroud)
nextInt()您提示选择的呼叫不会结束线路。所以对nextLine()after的第一次调用nextInt()将返回一个空字符串。要解决这个问题,请吃掉整数后面的空行,然后继续。