使用if(!“D”.equalsIgnoreCase(answer))不起作用比较String

时间:2015-01-07 10:34:00

标签: java

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

我正在尝试使用存款和抽奖来制作一个简单的应用程序。但是当我使用!equals来确保用户必须输入DW并且其他键将再次输入直到输入右键但是在此处它不起作用时它有一个错误输入DW无法识别输入无效。

我需要一些帮助。

4 个答案:

答案 0 :(得分:3)

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

if(!("D".equalsIgnoreCase(answer) || "W".equalsIgnoreCase(answer)))

if(!"D".equalsIgnoreCase(answer) && !"W".equalsIgnoreCase(answer))

答案 1 :(得分:3)

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

如果答案不是D,则编写错误消息。因为它不能同时存在,所以总是会收到错误消息。

答案 2 :(得分:2)

我认为你需要把

if(!"D".equalsIgnoreCase(answer) && !"W".equalsIgnoreCase(answer)){
          // your code
}

答案 3 :(得分:2)

De morgan's laws应该真的对你有帮助,值得一读:

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

将此应用于您的情况:

if(!"D".equalsIgnoreCase(answer) || !"W".equalsIgnoreCase(answer))

与:

相同
if(!("D".equalsIgnoreCase(answer) && "W".equalsIgnoreCase(answer))
   ↑
 Note that it's applied to the whole expression

哪些永远不会成为true

解决方案:

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