从String输入中退出While循环

时间:2018-04-21 21:01:50

标签: java while-loop

所以我正在使用简单的while循环和case打破用户菜单但有问题。对于我的情况,我需要使用char而不是int s(为了简单起见,我真的使用字符串Scanner)并且大多数情况下它都有效。但是当我输入D(我的退出情况)时,循环不会中断。不知道为什么,我已经多次使用int做了这件事而没有问题......

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");
   }
  }
 }
}

1 个答案:

答案 0 :(得分:1)

所以while(!choice.equals("D"))完成这项工作。请检查此链接:How do I compare strings in Java?。您比较了参考而不是值。