【问题标题】:Switch statement within Do-While loop doesn't exitDo-While 循环中的 switch 语句不退出
【发布时间】:2013-08-02 10:27:09
【问题描述】:

在我输入“stop”后,代码没有退出 - 出于某种原因。为什么? 逐步调试表明,在我输入“停止”后,它的值正好由 's'、't'、'o'、'p' 组成,没有任何换行符等 - 但是,代码仍然没有出口。谁能告诉我为什么?

import java.util.Scanner;

public class Application {
public static void main(String[] args) {
    Scanner input = new Scanner(System.in);

    // asking username
    System.out.print("Username: ");
    String username = input.nextLine();

    String inpText;
    do {
        System.out.print(username + "$: ");
        inpText = input.nextLine();
        System.out.print("\n");
        // analyzing
        switch (inpText) {
        case "start":
            System.out.println("> Machine started!");
            break;
        case "stop":
            System.out.println("> Stopped!");
            break;
        default:
            System.out.println("> Command not recognized");
        }
    } while (inpText != "stop");

    System.out.println("Bye!..");
}
}

【问题讨论】:

  • 阅读此内容:How do I compare strings in Java?,然后修复您的 while 条件。
  • 谢谢@jlordo。无法想象原因在于比较本身;并且链接的问题涵盖了所有内容。

标签: java loops java.util.scanner do-loops


【解决方案1】:
  • compare Strings 使用.equals() 而不是==,除非您真的知道自己在做什么。
inpText != "stop" //Not recommended
!"stop".equals(inpText) //recommended

无法为低于 1.7 的源级别打开字符串类型的值。 只允许可转换的 int 值或枚举变量

【讨论】:

  • 谢谢@rocketboy。 JDK 是 7u17,看起来这是一个正确比较的问题。然而,根据。 equals() 的规范不应该!inpText.equals("stop") 更正确吗?
  • String equals 是对称的,所以a.equals(b)b.equals(a) 相同。也就是说,如果 inpText = nullinpText.equals("stop") 可以抛出 NPE,但不会为 "stop".equals(inpText) 抛出它
【解决方案2】:

你正在用这段代码比较指针而不是字符串:

while (inpText != "stop");

应该是这样的:

while (!"stop".equals(inpText));

【讨论】:

  • 谢谢特里斯坦。但是,根据函数的规范, !inpText.equals("stop") 不应该更正确吗?
  • evictorov:通过将其写为 !"stop".equals(inpText) 您可以轻松避免任何可能的空指针。这只是我经常使用的一个小技巧。
【解决方案3】:

while (inpText != "stop"); 更改为 while (!(inpText.equals("stop")));

【讨论】:

    【解决方案4】:

    如果你的 JDK 是 1.6 或更低版本,你不能 switch() 字符串

    附: 切换字符串可能不是最好的解决方案是的,在 java 1.6 中你只能切换 int、boolean、double、long 和 float 我相信。

    【讨论】:

    • 谢谢莫辛。我的是 7u17。
    猜你喜欢
    • 2022-01-03
    • 2021-03-08
    • 2013-10-21
    • 1970-01-01
    • 1970-01-01
    • 2019-12-17
    • 1970-01-01
    • 1970-01-01
    • 2020-05-07
    相关资源
    最近更新 更多