2015-01-07 75 views
0
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它不能识别通知输入无效。比较字符串使用if(!“D”.equalsIgnoreCase(answer))不起作用

我需要一些帮助。

回答

3

如果答案必须是d或W,条件应该是:

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

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

在第一线的&&更换||

如果答案不是D或不是W,那么你会写出错误信息。因为它不能同时出现,你总会得到错误信息。

+0

首先注意到错误,但是您可能希望在答案中使用格式(即'||'和'&&') –

2

我认为你需要把

if(!"D".equalsIgnoreCase(answer) && !"W".equalsIgnoreCase(answer)){ 
      // your code 
} 
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

解决方案:

正如其他人已经建议,与&&更换||