Java 使用if(!”D“.equalsIgnoreCase(应答))比较字符串不起作用

Java 使用if(!”D“.equalsIgnoreCase(应答))比较字符串不起作用,java,Java,我正试着用存款和取款做一个简单的申请。但是当我使用时,它有一个bug!等于以确保用户必须输入D或W,并且其他键将再次输入,直到输入右键,但在这里它不起作用,并且输入D或W无法识别,告知输入无效 我需要一些帮助。如果答案必须是D或W,则条件应为: if(!"D".equalsIgnoreCase(answer) || !"W".equalsIgnoreCase(answer)){ System.out.println("The answer is invalid!Please i

我正试着用存款和取款做一个简单的申请。但是当我使用
时,它有一个bug!等于
以确保用户必须输入
D
W
,并且其他键将再次输入,直到输入右键,但在这里它不起作用,并且输入
D
W
无法识别,告知输入无效


我需要一些帮助。

如果答案必须是D或W,则条件应为:

if(!"D".equalsIgnoreCase(answer) || !"W".equalsIgnoreCase(answer)){
         System.out.println("The answer is invalid!Please input again!");
         answer = input.nextLine();
    }else if(answer.equalsIgnoreCase("D")){
        System.out.println("Enter deposite ammount: ");
        depositAmmount = input.nextDouble();
        System.out.printf("adding %.2f to account1\n\n", depositAmmount);
        acc1.Credit(depositAmmount);

        //display balance
        System.out.format("ballance of account1 is: %.2f\n", acc1.getBallance());
        System.out.format("ballance of account2 is: %.2f\n\n", acc2.getBallance());
    }
    else if(answer.equalsIgnoreCase("W")){
        System.out.println("Enter withdraw ammount: ");
        withdrawAmmount = input.nextDouble();
        System.out.printf("differing %.2f to account1\n\n", withdrawAmmount);
        acc1.Withdraw(withdrawAmmount);

        //display balance
        System.out.format("ballance of account1 is: %.2f\n", acc1.getBallance());
        System.out.format("ballance of account2 is: %.2f\n", acc2.getBallance());
    }


将第一行中的
|
替换为
&&


如果答案不是D或不是W,您将写入错误消息。因为答案不能同时是D和W,所以您总是会收到错误消息。

我认为您需要将

if(!"D".equalsIgnoreCase(answer) && !"W".equalsIgnoreCase(answer))
应该真的对你有帮助,值得一读:

if(!"D".equalsIgnoreCase(answer) && !"W".equalsIgnoreCase(answer)){
          // your code
}
将此应用于您的情况:

(not a) OR (not b)  ⟷  not (a AND b)
同:

if(!"D".equalsIgnoreCase(answer) || !"W".equalsIgnoreCase(answer))
这永远不可能是真的

解决方案:


正如其他人已经建议的,将
|
替换为
&

第一个注意到错误的人,但是您可能希望在回答中使用格式(即
|
&
if(!"D".equalsIgnoreCase(answer) || !"W".equalsIgnoreCase(answer))
if(!("D".equalsIgnoreCase(answer) && "W".equalsIgnoreCase(answer))
   ↑
 Note that it's applied to the whole expression