Java 从字符串输入退出While循环
因此,我正在编写一个用户菜单,使用一个简单的Java 从字符串输入退出While循环,java,while-loop,Java,While Loop,因此,我正在编写一个用户菜单,使用一个简单的,而循环和case中断,但有一个问题。对于我的案例,我需要使用chars而不是ints(为了简单起见,实际上使用了字符串扫描仪),并且在大多数情况下它都可以工作。但当我进入D(我的退出案例)时,循环不会中断。不知道为什么,我已经用ints做了很多次了,没有任何问题 import java.util.Scanner; public class Postfix_Notation { public static void main(String[] ar
,而循环和case
中断,但有一个问题。对于我的案例,我需要使用char
s而不是int
s(为了简单起见,实际上使用了字符串扫描仪),并且在大多数情况下它都可以工作。但当我进入D(我的退出案例)时,循环不会中断。不知道为什么,我已经用int
s做了很多次了,没有任何问题
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");
}
}
}
}
所以,而(!choice.equals(“D”)
做这项工作。检查此链接:。您比较了引用而不是值。我在编译器中对此进行了测试,以确保。事实上,这是他们代码的唯一问题。测试了这个,它成功了,非常感谢!所以我读了你给我的链接,我有一个后续问题。所以“Choice”是一个引用或对象,“D”的值正确吗?因此,通过将引用与值进行比较,它不会执行任何操作,但编译器不应该抛出错误吗?我知道这与比较不同的数据类型不同,但在逻辑上仍然不正确。引用是指向内存中对象的指针。“Choice”和“D”都有引用,但您不想检查它是否在内存中的同一位置,您感兴趣的是“Choice”的值和“D”的值是否相同,您并不真正关心它们存储在何处