1

我有一台扫描仪询问一些偏好。它创建一个介于 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*");

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成为一个空白列表。为什么会发生这种情况,我该如何解决?

4

3 回答 3

5

您可能在最后一个输入之后读取换行符,而不是真正的下一行。尝试:

int choice = input.nextInt();

input.nextLine(); // <--- Eat it here!
String location;
switch(choice){
    case 0:
        Syst...

提示您选择的nextInt()呼叫不会结束该行。所以第一次调用nextLine()afternextInt()将返回一个空字符串。为了解决这个问题,吃掉整数后面的空行,然后继续。

于 2013-10-20T21:10:58.257 回答
0

将 nextLine 放在 read 之后切换之前。

System.out.print("Digite um número ente 1 e 9: ");
int opc = read.nextInt();
read.nextLine();
switch(opc) {

并使用 nextLine() 读取您的值

case 6:
    String[] procurados = read.nextLine().split(" ");
于 2019-03-29T14:03:55.843 回答
0

我遇到了和你一样的问题。尝试:

case 'f' :
                System.out.println("Enter a word or phrase to be found:");
                scnr.nextLine();
                String phrase = scnr.nextLine(); //
于 2018-10-11T19:03:27.830 回答