[英]Arrays in for loops
I have an array called blockHeights
, which contains 3 values inside of it, namely 1,2,3. 我有一个名为
blockHeights
的数组,其中包含3个值,即1,2,3。 So blockHeights[0]
is equal to 1. 因此,
blockHeights[0]
等于1。
I also have a loop: 我也有一个循环:
for (int i = 1; i <= blockHeights.length; i++)
In the first time around the loop, I want to create a variable called totalBlockHeights
where it is 在第一次循环时,我想在其中创建一个名为
totalBlockHeights
的变量
int totalBlockHeights = blockHeights[0] + blockHeights [1] + blockHeights [2];
However, in the next loop I want that variable to change, so that it only adds blockHeights[1]
and blockHeights[2]
together, ignoring blockHeights[0]
. 但是,在下一个循环中,我希望更改该变量,以便仅将
blockHeights[1]
和blockHeights[2]
在一起,而忽略blockHeights[0]
。
How would I go about doing this? 我将如何去做呢?
Try the following (I'm assuming the third iteration should only include blockHeights[2]
, following the pattern): 尝试以下操作(我假设第三次迭代应遵循该模式仅包括
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
}
Well, if you want the sum of your array, and the sum of the array without first value 好吧,如果您想要数组的总和,而没有第一个值的数组的总和
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]));
this way you only loop once 这样你只循环一次
you can perform this on two for loop outer loop for (int i = 1; i <= blockHeights.length; i++)
, and in inner loop (take a variable j) you can do like int totalBlockHeights = totalBlockHeights + blockHeights[j]
, and for i<j
, you can just continue the for loop. 您可以在两个for循环外部循环上执行此操作
for (int i = 1; i <= blockHeights.length; i++)
,在内部循环(采用变量j)中,您可以像int totalBlockHeights = totalBlockHeights + blockHeights[j]
,对于i<j
,您可以继续执行for循环。
as answered by btrs20 如btrs20回答
Try following code: 尝试以下代码:
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);
This will print: 这将打印:
6
5
You dont need two for to achieve that. 您不需要两个就可以实现。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.