java数组循环,用于保存上一次迭代的结果

时间:2018-03-30 14:30:56

标签: java

我真的需要帮助,我是编程的新手,

我需要一个循环来帮助迭代这个数组并保存下一次迭代的余额结果。就像从银行账户中提取一样。

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] 使用循环?

2 个答案:

答案 0 :(得分:0)

是的,你可以。

正如the documentation所说:

  

for语句提供了一种迭代一系列值的简洁方法。

答案 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];
}