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.”
I am modifying your code to re-initialize your scanner reference before reading new option..
Rest, you can read from the link I provided, to know the difference between various methods for reading user input..