【问题标题】:Java why wont scanner work inside a switchJava为什么扫描仪不能在开关内工作
【发布时间】:2013-10-20 21:08:15
【问题描述】:

我有一台扫描仪询问一些偏好。它创建了一个介于 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 成为一个空白列表。 为什么会发生这种情况,我该如何解决?

【问题讨论】:

标签: java input switch-statement java.util.scanner


【解决方案1】:

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

int choice = input.nextInt();

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

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

【讨论】:

  • 对这个输入使用新的扫描仪怎么样?
  • @nazar_art:完全偏离主题,很可能是错误的,或者我不明白你想说什么。
  • 这是我的问题...谢谢!当我被允许时,我会在 6 分钟内排除你的答案
  • @Martijn Courteaux 我想知道在执行int choice = input.nextInt(); 之后是否可以使用新的扫描仪进行输入?
  • 嗯,这是错误的,原因有很多。 1)您正在创建不必要的对象。 2) 如果底层输入流包装在来自文件的 BufferedInput 流中,这可能会失败。 3)他的问题是扫描仪的明确定义的行为,应该根据需要简单地处理。 4) 创建一个新的 Scanner 实在是太丑了。
【解决方案2】:

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

case 'f' :
                System.out.println("Enter a word or phrase to be found:");
                scnr.nextLine();
                String phrase = scnr.nextLine(); //

【讨论】:

    【解决方案3】:

    将 nextLine 放在 read 之后的 switch 之前。

    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(" ");
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-06-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-23
      • 1970-01-01
      相关资源
      最近更新 更多