[英]Arrays in for loops
我有一个名为blockHeights
的数组,其中包含3个值,即1,2,3。 因此, blockHeights[0]
等于1。
我也有一个循环:
for (int i = 1; i <= blockHeights.length; i++)
在第一次循环时,我想在其中创建一个名为totalBlockHeights
的变量
int totalBlockHeights = blockHeights[0] + blockHeights [1] + blockHeights [2];
但是,在下一个循环中,我希望更改该变量,以便仅将blockHeights[1]
和blockHeights[2]
在一起,而忽略blockHeights[0]
。
我将如何去做呢?
尝试以下操作(我假设第三次迭代应遵循该模式仅包括blockHeights[2]
):
for (int i = 1; i <= blockHeights.length; i++) {
int totalBlockHeights;
for (int j = i - 1; j < blockHeights.length; j++) { // all block heights from here onwards
totalBlockHeights += blockHeights[j];
}
// do whatever
}
好吧,如果您想要数组的总和,而没有第一个值的数组的总和
int totalBlockHeights = 0;
for(int i = 0; i < blockHeights.length; i++){
totalBlockHeights += blockHeights[i];
}
System.out.println(totalBlockHeights);
System.out.println("totalBlockHeights without first value = " + (totalBlockHeights - blockHeights[0]));
这样你只循环一次
您可以在两个for循环外部循环上执行此操作for (int i = 1; i <= blockHeights.length; i++)
,在内部循环(采用变量j)中,您可以像int totalBlockHeights = totalBlockHeights + blockHeights[j]
,对于i<j
,您可以继续执行for循环。
如btrs20回答
尝试以下代码:
public class Loop {
public static void main(String[] argv) {
int[] blockHeights = new int[] {1, 2, 3};
int totalBlockHeights = 0;
for(int i = 0; i < blockHeights.length; i++) {
totalBlockHeights = 0;
for(int j = i; j < blockHeights.length; j++) {
totalBlockHeights += blockHeights[j];
}
System.out.println(totalBlockHeights);
}
}
}
int[] blockHeights = new int[] { 1, 2, 3 };
int totalBlockHeights = 0;
int customBlockHeights = 0;
for (int i = 0; i < blockHeights.length; i++) {
totalBlockHeights += blockHeights[i];
if (i == 0) {
continue;
}
customBlockHeights += blockHeights[i];
}
System.out.println(totalBlockHeights);
System.out.println(customBlockHeights);
这将打印:
6
5
您不需要两个就可以实现。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.