Reputation: 3
So I am writing a user menu using a simple while
loop and case
breaking but having an issue. I need to use char
s instead of int
s for my cases (really using a string Scanner
for simplicity) and for the most part it works. But when I enter D (my exit case) the loop does not break. Not sure why, I have done this with int
s many times without an issue...
import java.util.Scanner;
public class Postfix_Notation {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String choice = "Z";
while (choice != "D") {
System.out.println("Enter A, B or C to perform an operation or enter D to exit.");
System.out.println("A- Evaluate a user input postfix expressions");
System.out.println("B- Convert, display infix expressions to postfix expressions then evaluate and display the result of thepostfix expression");
System.out.println("C- Reads words from a the text file (hangman.txt) in a LinkedList and use an iterator on it to displays all the words (duplicates allowed) in descending alphabetical order");
System.out.println("D- Exit");
choice = new Scanner(System.in).next();
switch (choice) {
case "A":
System.out.println("Enter a string: ");
String s = new Scanner(System.in).next();
System.out.println("All possible permutations of " + s + " are: ");
System.out.println("\n");
break;
case "B":
Scanner input2 = new Scanner(System.in);
System.out.println("Enter a hex string: ");
String hexString = input2.next();
System.out.println("The decimal equivalent of " + hexString + " is " + (hexString));
System.out.println("\n");
break;
case "C":
Scanner input = new Scanner(System.in);
System.out.println("Enter a binary string: ");
String binaryString = input.next();
System.out.println("The decimal equivalent of " + binaryString + " is " + (binaryString));
System.out.println("\n");
break;
case "D":
System.out.println("Program Ended");
break;
default:
System.out.println("Invalid Input");
}
}
}
}
Upvotes: 0
Views: 2436
Reputation: 5689
So while(!choice.equals("D"))
do the job. Check this link: How do I compare strings in Java?. You compared references instead of values.
Upvotes: 1