Question

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!..");
}
}
Was it helpful?

Solution

  • 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

OTHER TIPS

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

P.S. 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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top