如果用Java中的语句撤销方法

时间:2014-08-11 17:31:10

标签: java

目标是创建withdraw方法,只有当withdrawAmount不超过该余额时才会将withdrawAmount从当前余额减去。如果是,那么我们打印一条消息并保持平衡不变。使用 if ... else ,例如

,这很容易
public void withdraw(double withdrawAmount)
{
    if (withdrawAmount > 0.0)
        if (withdrawAmount > balance)
            System.out.println("Withdrawal amount exceeded account balance");
        else
            balance = balance - withdrawAmount;
}

有没有办法在不使用 if ... else 结构或&& 及其兄弟的情况下实现相同的效果?

4 个答案:

答案 0 :(得分:0)

是的,使用例外。

在异常情况下会抛出异常

 public void withdraw(double amount) {
   if (amount > 0.0d) {
     throw new IllegalArgumentException("Cannot withdraw a negative amount");
   }
   if (amount > balance) {
     throw new IllegalStateException("Cannot overdraw an account");
   }
   balance = balance - amount;
 }

当然,这段代码可以作为一个爱好示例,但它不是线程安全的。

假设您不想抛出异常,您也可以提前退出"

   if (amount > balance) {
     System.out.println("Withdrawl amount exceeded account balance");
     return;
   }
   balance = balance - amount;

答案 1 :(得分:0)

根据OP的评论,该问题实际上是Else,而不是If

public void withdraw(double withdrawAmount)
{
    if (withdrawAmount > 0.0 && withdrawAmount > balance)
    {
        System.out.println("Withdrawal amount exceeded account balance");
        return;
    }

    balance = balance - withdrawAmount;
}

答案 2 :(得分:0)

只是肛门,避免任何if或布尔运算符:

String msg = (withdrawAmount > balance) ? "Withdrawl amount exceeded account balance\n" : "";
double delta = (withdrawAmount > balance) ? 0.0d : Math.max(withdrawAmount,0.0d);
System.out.print( msg ); // prints nothing if balance high enough
balance -= delta;        // delta is 0 unless balance is high enough & wA is positive

答案 3 :(得分:0)

您可以通过真正的无分支代码来实现:

private double balance = -10;

private String[] negativeWaring = { "", "Withdrawing negative amnt!\n" };
private String[] exceedWaring = { "", "Withdrawing exceeds balance!\n" };

public static int isNegative(double d) {
    long bits = Double.doubleToLongBits(d);
    bits = bits >>> 63;
    return (int) bits;
}

void withdraw(double amnt) {
    int negative = isNegative(amnt);
    int exceed = isNegative(balance - amnt);

    exceed *= 1 - negative; // only apply exceed flag if amnt is positive
    System.out.print(negativeWaring[negative]);
    System.out.print(exceedWaring[exceed]);
    balance += amnt * negative * exceed;
}

对于负数,isNegative()方法将返回1,对于正数,0方法将返回System.out.print()

修改

我不确定{{1}}究竟是如何工作的,如果有某些条件,那么你的代码就不会真正无分支。