[英]Why does my while loop not work for counting the sum of an array and displaying the array
I am attempting to display a random array whilst also displaying the sum of that array yet I can't get it to work, I know how to do it with a for loop but I was instructed on doing a while loop instead, any ideas? 我试图显示一个随机数组,同时还显示该数组的总和,但是我无法使其正常工作,我知道如何使用for循环来完成此工作,但有人指示我做一个while循环,有什么想法吗?
private void SumOfArray() {
myWindow.clearOut();
int total = 0;
int[] a = new int[4];
int i;
i = 0;
while (i < a.length) {
i++;
a[i] = 1 + (int) (Math.random() * 10);
}
i = 0;
while (i < a.length) {
i++;
myWindow.writeOutLine(a[i]);
}
while (i < a.length) {
total += a[i];
i++;
}
myWindow.writeOutLine(total);
}
You are incrementing i
prematurely, causing an ArrayIndexOutOfBoundsException
. 您过早地增加了
i
,导致ArrayIndexOutOfBoundsException
。 You should increment it after assigning a number of a[i]
. 您应该在分配
a[i]
数之后增加它。
Change it to 更改为
while (i < a.length) {
a[i] = 1 + (int) (Math.random() * 10);
i++;
}
Now the loop behaves similar to a for loop - ie i
is incremented after all the other statements of the loop's body. 现在,该循环的行为类似于for循环-即,在循环主体的所有其他语句之后,
i
递增。
Your other loops should also be fixed, and in fact, all your loops can be merged into a single loop : 您的其他循环也应该是固定的,实际上,所有循环都可以合并为一个循环:
int i = 0;
while (i < a.length) {
a[i] = 1 + (int) (Math.random() * 10);
myWindow.writeOutLine(a[i]);
total += a[i];
i++;
}
另外,您有3个while循环和两次将0
分配给i
...的地方。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.