Java try catch返回false变量

时间:2013-12-16 15:14:42

标签: java variables if-statement try-catch

当我将字符串''''的值输入为'是'时,if语句就像是执行System.out.println一行(“请继续购物”),就好像决定的值不是“是” );我该怎么做才能解决这个问题?以下是问题所在的类:

 //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");
        }
}

3 个答案:

答案 0 :(得分:1)

要比较String对象,请使用equals(String myValue)方法,而不是==

答案 1 :(得分:1)

要比较java中的对象,请使用.equals()方法而不是“==”运算符

变化

if(decision == "Yes")

if("Yes".equals(decision))

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

 if("Yes".equalsIgnoreCase(decision))

答案 2 :(得分:0)

这里 - > if(decision == "Yes")

使用

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