如果和Switch一样的task,结果不一样?

If and Switch same task, different results?

我有一个 switch 和一个 if 语句,它们是等价的。他们都应该拿一个字符串,如果是,则做某事,如果不是,则做另一件事。无论输入什么,if 语句都不做任何事情,但 switch 语句会做。这是为什么?

这是 if 语句:

if (yes.equals("yes")){
    System.out.println ("Enter your first number");
    fnum = x.nextDouble();
    System.out.println ("Enter your second number");
    snum = x.nextDouble();
    calculations(fnum, snum);
}
if (yes.equals("No")) {
    System.out.println("okay, bye then!");
}

这里是开关:

switch (yesno){
    case "yes":  
        System.out.println ("Enter your first number");
        fnum = x.nextDouble();
        System.out.println ("Enter your second number");
        snum = x.nextDouble();
        calculations(fnum, snum);
        break;
    case "no":
        System.out.println("k bye");

这不是重复的,因为问题出在 if 语句中。我的开关被标记为重复。

I have a switch and an if statement, and they are equivalent.

实际上,它们并不等价:

  • if 版本正在检查 "yes""No"。而是检查 "yes""no" 的切换版本。由于在这两种情况下检查都区分大小写,因此如果输入是 "no" ... 或 "No".

  • ,您将得到不同的结果
  • 两个版本检查不同的变量;即 yesyesno。这可能会有所不同,具体取决于上下文。

其中任何一个都可以解释您所看到的不同行为。


I thought that yes and yesno would be equal, but they weren't...? Any idea why?

嗯,显然名称不同,所以它们不能是相同的变量。

然而,它们是不同的变量这一事实并不一定意味着它们具有不同的决定了代码的行为。

当然,如果 yesno 包含适当的 "yes""no" 值并且 yes 包含其他内容(例如 ""),那么给出你正在观察的行为。 (显然这是一个假设诊断。如果您想要更具体的答案,请向我们展示相关代码。)