【问题标题】:Why does this switch statement not work? [duplicate]为什么这个 switch 语句不起作用? [复制]
【发布时间】:2016-01-13 09:59:23
【问题描述】:
import java.util.Scanner;

public class VerticalWire {
    public static void main(String[] args)
    {  
        Scanner in = new Scanner(System.in);
        System.out.println("how many wires");
        String howManyWires = in.next();

        switch(howManyWires) {
            case "3":
            {
                 System.out.println("true");
                 break;
            }

            case "3 5":
            {
                 System.out.println("false");break;}
            }
     }
}

我测试了如果我输入“3 5”它会返回 true,即使我认为它应该返回 false! 怎么了?

【问题讨论】:

  • 你认为in.next() 是做什么的?你为什么这么认为?
  • in.next() 只读取第一个数字。使用nextLine()
  • 阅读Scanner#next 的实际作用,然后改用Scanner#nextLine

标签: java string switch-statement hashcode


【解决方案1】:

使用in.nextLine() 代替in.next()

scanner.next() 的文档指出

从此扫描器中查找并返回下一个完整的令牌。

所以当你输入3 5作为输入时,当你调用下一个方法时它只会读取3,如果你再次调用下一个方法,它会读取5。

【讨论】:

  • 他们为什么要这样做? (我知道答案,但你需要告诉 OP ;))
  • @MadProgrammer - 你不必说 - 我知道答案。我们知道你知道:P
  • @TheLostMind 人们经常把我误认为是 OP ;)
  • @MadProgrammer - 如果他们知道如何将鼠标悬停在一个人的名字上:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多