Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: How to use a switch statement [duplicate]

Possible Duplicate:
How do I compare strings in Java?

I am having trouble understanding how to use a Java switch statement. After executing a method in one of the case statements, it still then goes to the default statement and runs that too. Here's the code:

Scanner scanner = new Scanner(System.in);
String option = null;

while (option != "5") {
    ShowMenu();
    option = scanner.nextLine();
    switch (option) {
        case "1": ViewAllProducts(); break;
        case "2": ViewProductDetails(scanner); break;
        case "3": DeleteProduct(scanner); break;
        case "4": AddProduct(scanner); break;
        case "5": break;
        default: System.out.println("Invalid option. Please try again."); break;
    }
}

The above code is in the main method. After running case "4" for example, it prints "Invalid option."

like image 858
Matt Avatar asked Jul 15 '26 02:07

Matt


2 Answers

  while (!option.equals("5")){...}

Use .equals() for string compare.

== compare string refrences(Memory location) .equals() compare string value

  • see here
like image 141
Samir Mangroliya Avatar answered Jul 17 '26 15:07

Samir Mangroliya


You are comparing Strings with == in your while condition (which compares references instead of values - use equals method for value equality), while loop should be changed to following -

while (!option.equals("5"))

It works in C# flawlessly because of operator overloading while operator overloading is not allowed in java (though "+" is overloaded for String and numbers)

like image 37
Premraj Avatar answered Jul 17 '26 16:07

Premraj



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!