简体   繁体   中英

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. 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.
 inpText != "stop" //Not recommended !"stop".equals(inpText) //recommended 

Cannot switch on a value of type String for source level below 1.7. Only convertible int values or enum variables are permitted

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"); to while (!(inpText.equals("stop")));

If your JDK is 1.6 or lower you can't switch() on a 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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