是否可以在一行代码中执行两种不同的“+=”和“-=”操作?
Is it possible to perform two different "+=" and "-=" operations in one line of code?
我刚开始自学 java 我想知道是否有一个操作(可能是 "and then" 操作)可以让我在同一行上执行两个数学计算。保持 "balance" 的更新总数很重要。这是我的代码:
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);
}
没有 Java 语法可以做到这一点,但您仍然可以使用简单的数学运算来做到这一点。
您想做的事情:
X = X - y + z
这里不需要两个作业。您只需减去一个值并添加另一个值,然后再对 X 执行单个赋值。
您只需一行即可完成:
System.out.println(balance = balance - withdrawalAmount + depositAmount);
我刚开始自学 java 我想知道是否有一个操作(可能是 "and then" 操作)可以让我在同一行上执行两个数学计算。保持 "balance" 的更新总数很重要。这是我的代码:
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);
}
没有 Java 语法可以做到这一点,但您仍然可以使用简单的数学运算来做到这一点。
您想做的事情:
X = X - y + z
这里不需要两个作业。您只需减去一个值并添加另一个值,然后再对 X 执行单个赋值。
您只需一行即可完成:
System.out.println(balance = balance - withdrawalAmount + depositAmount);