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."
while (!option.equals("5")){...}
Use .equals() for string compare.
== compare string refrences(Memory location)
.equals() compare string value
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With