Java if ... else语句无法正常工作

时间:2015-04-08 00:33:07

标签: java if-statement

public double transferSavingToChecking(double Tamount2)
{
    //check if enough to transfer
    if(Tamount2 > Saving_Balance)
        System.out.println("Transfer failed. You don't have enough     balance in the saving account!");
    else
        System.out.println("You have successfully transferred $" + Tamount2 + " from the saving account to the checking account");
        Saving_Balance = Saving_Balance - Tamount2;
        Checking_Balance = Checking_Balance + Tamount2;

    return Checking_Balance;
}

转账时,if...else语句每次都会运行。例如,即使在transfer > balance时,输出也反映出转移仍然发生,即使它说它失败了。

1 个答案:

答案 0 :(得分:4)

您需要在if / else块的内容周围添加花括号。如果/ else语句以下列方式编写:

if (condition) {
    // do something
} else {
    // do something else
}

如果错过花括号,只有if / else之后的第一个语句被认为是if / else块的一部分。

将您的代码更改为以下内容:

public double transferSavingToChecking(double Tamount2) {
    //check if enough to transfer
    if(Tamount2 > Saving_Balance) {
        System.out.println("Transfer failed. You don't have enough     balance in the saving account!");
    } else {
        System.out.println("You have successfully transferred $" +     Tamount2 + " from the saving account to the checking account");
        Saving_Balance=Saving_Balance - Tamount2;
        Checking_Balance=Checking_Balance + Tamount2;
    }
    return Checking_Balance;
}