我真的需要帮助,我是编程的新手,
我需要一个循环来帮助迭代这个数组并保存下一次迭代的余额结果。就像从银行账户中提取一样。
int[] loanAmount= {2,4,8,12};
int balance = 10;
int newBalance = 0;
newBalance = balance - loanAmount[0];
System.out.println(newBalance);
newBalance = newBalance - loanAmount[1];
System.out.println(newBalance);
newBalance = newBalance - loanAmount[2];
System.out.println(newBalance);
我可以通过for循环[i]来实现这个目标吗?
for(int i=0;i<loanAmount.length;i++){
newBalance = balance - loanAmount[i];
System.out.println(newBalance);
}
所以这将迭代数组loanAmount并从int balance中减去每个数组元素。
如何从balance-loanAmount [0]中减去loanAmount [1] 使用循环?
答案 0 :(得分:0)
答案 1 :(得分:0)
你可以这样做:
int[] loanAmount= {2,4,8,12};
int balance = 10;
int newBalance = balance;
for(int i = 0; i < len; ++i){
newBalance -= loanAmount[i];
// This is the same as doing :
// newBalance = newBalance - loanAmount[i];
}