簡體   English   中英

Do-While循環中的Switch語句不會退出

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

由於某種原因,在我輸入“停止”后代碼不會退出。 為什么? 逐步調試顯示,在我輸入“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!..");
}
}
  • 比較字符串使用.equals()而不是== ,除非你真的知道你在做什么。
 inpText != "stop" //Not recommended !"stop".equals(inpText) //recommended 

如果源級別低於1.7,則無法為String類型的值打開。 只允許使用可轉換的int值或枚舉變量

您正在使用這段代碼比較指針而不是字符串:

while (inpText != "stop");

應該是這樣的:

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

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

如果JDK為1.6或更低,則無法在String上切換()

PS上的字符串切換可能不是最好的解決方案在java 1.6中你只能切換int,boolean,double,long和float我相信。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM