Say I have 10 integer variables, uname -r
to x1
.
I have an integer array, as follows:
x10
I would like to specify the elements of the array as follows:
Int[] countup = new Int[10];
And so on until countup[9] is the sum of countup[0] = x1;
countup[1] = x1 + x2;
countup[2] = x1 + x2 + x3;
to x1
.
I could do this manually if it was just 10 elements, but in the actual program I'm writing, there's over 100 elements of the array. Is there any way to set the variables of this array quickly?
答案 0 :(得分:4)
for循环是你最好的选择,只需将你的10(或100)个整数放入它自己的数组中,然后在第二个数组上循环引用第一个数组的索引:
int[] xNumbers = { x1, x2, x3, ... x10 };
int[] countup = new int[10];
//Set the 0 index so we don't have to do extra check inside the for loop
//for out-of-bounds exception
countup[0] = xNumbers[0];
for (int i = 1; i < 10; i++) {
//countup[i-1] is why we set index 0 outside of the loop
countup[i] = xNumbers[i] + countup[i-1];
}
由于countup[i-1]
是前一个数字的总和,之前的添加已经为您完成。如果您不知道for循环是什么,可以找到更多信息here
答案 1 :(得分:1)
我想在Java 8中找到一种方法,另一个答案可能更好:
这就是我所拥有的,但它似乎是多余的,浪费时间,但我不熟悉Java 8:
public static void main(String[] args) {
int[] arr = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int length = arr.length;
for (int i = 1; i < length; i++) {
System.out.println(Arrays.toString(Arrays.copyOfRange(arr, 0, i + 1)));
arr[i] = Arrays.stream(Arrays.copyOfRange(arr, 0, i + 1)).sum();
}
System.out.println(Arrays.toString(arr));
}
arr[9]
是[1, 3, 7, 15, 31, 63, 127, 255, 511, 1023]
我相信我也以不同的方式解释了这个问题。我想他想在index[i]
中得到所有先前元素的总和。
如果我对你的问题的解释是正确的,那么在没有Java 8的情况下,使用2个循环:
int[] array = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int length = array.length;
for(int i = 1; i < length; i++) {
int sumSoFar = 0;
for(int j = 0; j <= i; j ++) {
sumSoFar += array[j];
}
array[i] = sumSoFar;
}
答案 2 :(得分:1)
简洁地:
int[] xNums = { /*your x numbers here*/ };
int[] resultArray = new int[xNums.length];
for(int n = 0; n < xNums.length; n++)
{
for(int i = 0; i <= n; i++)
{
resultArray[n]+=xNums[i];
}
}
希望有意义!