2015-01-07 104 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

解決方案:

正如其他人已經建議,與&&更換||