2013-12-16 44 views
0

當我輸入字符串'決定'的值爲'是'時,if語句就像通過執行System.out.println行的行爲就好像決定的值不是'是'一樣(「請繼續購物」);我能做些什麼來解決這個問題?下面是類的問題是:Java嘗試捕獲返回虛假變量

//paying for this instance of a basket 
public void payBasket(double cash){ 
    String decision; 
    double balance; 
    System.out.println("You have £" +cash); 
    decision = null; 
    if(cash > endTotal) 
    {System.out.println("You have enough money to pay for this basket"); 
    } 
    else 
    {System.out.println("You need more money before you can pay for these items");}; 
    BufferedReader reader; 
    reader = new BufferedReader(new InputStreamReader(System.in)); 
    System.out.println("Would you like to pay for this basket?"); 
    try{ 
    decision = reader.readLine(); 
    } 
    catch (IOException ioe){ 
     System.out.println("an unecpected error"); 
    } 

    if(decision == "Yes"){balance = endTotal - cash; 
     System.out.println("Your current balance is " + balance);} 
     else {System.out.println("Please continue shopping"); 
     } 
} 
+0

使用.equals()比較字符串..! – BlackPOP

+0

http://stackoverflow.com/questions/20596624/cant-get-java-to-assign-a-value-to-a-variable-using-if-statement –

回答

1

比較Java中使用.equals對象()方法,而不是「==」操作符

變化

if(decision == "Yes") 

if("Yes".equals(decision)) 

,如果你想忽略大小寫使用.equalsIgnoreCase()方法

if("Yes".equalsIgnoreCase(decision)) 
1

比較String對象,使用方法equals(String myValue),不==

0

這裏 - >if(decision == "Yes")

使用

if(descision.equals("Yes"));