简体   繁体   English

Do-While循环中的Switch语句不会退出

[英]Switch statement within Do-While loop doesn't exit

The code doesn't exit after I type "stop" - for some reason. 由于某种原因,在我输入“停止”后代码不会退出。 Why? 为什么? Step-by-step debugging shows that after I enter "stop" it's value consists of exactly 's','t','o','p' without any line breaks, etc. - however, the code still goesn't exit. 逐步调试显示,在我输入“stop”之后,它的值由's','t','o','p'组成,没有任何换行符等等。但是,代码仍然没有出口。 Could anyone tell why, please? 谁能说出原因,拜托?

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!..");
}
}
  • To compare Strings use .equals() and not == , unless you really know what you are doing. 比较字符串使用.equals()而不是== ,除非你真的知道你在做什么。
 inpText != "stop" //Not recommended !"stop".equals(inpText) //recommended 

Cannot switch on a value of type String for source level below 1.7. 如果源级别低于1.7,则无法为String类型的值打开。 Only convertible int values or enum variables are permitted 只允许使用可转换的int值或枚举变量

You are comparing pointers not strings with this piece of code: 您正在使用这段代码比较指针而不是字符串:

while (inpText != "stop");

Should be something like this: 应该是这样的:

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

change while (inpText != "stop"); 改变while(inpText!=“停止”); to while (!(inpText.equals("stop"))); to while(!(inpText.equals(“stop”)));

If your JDK is 1.6 or lower you can't switch() on a String 如果JDK为1.6或更低,则无法在String上切换()

PS switching on a String is probably not the best solution Yeah in java 1.6 you can only switch int, boolean, double, long, and float I believe. PS上的字符串切换可能不是最好的解决方案在java 1.6中你只能切换int,boolean,double,long和float我相信。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM