是否可以在一行代码中执行两个不同的“ + =”和“-=”操作?

时间:2019-03-14 03:46:10

标签: java math operation

我刚刚开始自学Java,我想知道是否有一个操作(也许是“然后”操作)可以使我在同一行上执行两个数学计算。保持“余额”的更新总数很重要。这是我的代码:

public static void main(String[] args) {
  double balance = 5400d;
  double withdrawalAmount = 2100d;
  double depositAmount = 1100d;

  //Total Balance after primary transactions 
  // (This line of code works but I want to update "balance" after every calculation
  System.out.println(balance - withdrawalAmount + depositAmount); 

  //This updates the balance after withdrawing money    
  System.out.println(balance -= withdrawalAmount);

  //This updates balance after depositing money    
  System.out.println(balance += depositAmount);

  //Here is where I was trying to combine both operations but it did not like this very much    
  System.out.println(balance -= withdrawalAmount && balance += depositAmount);
  }

2 个答案:

答案 0 :(得分:8)

没有Java语法可以做到这一点,但是您仍然可以使用简单的简单数学来做到这一点。

您想这样做:

X = X  - y + z

这里不需要两个作业。您只需减去一个值,然后再添加另一个值,然后再将单个赋值回X。

答案 1 :(得分:2)

您只需一行即可完成

System.out.println(balance = balance - withdrawalAmount + depositAmount);