gpt4 book ai didi

java - 从字符串输入中退出 While 循环

转载 作者:行者123 更新时间:2023-12-02 11:20:26 25 4
gpt4 key购买 nike

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

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

最佳答案

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

关于java - 从字符串输入中退出 While 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49960181/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com