Reputation: 123
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?
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);
}
Upvotes: 1
Views: 70
Reputation: 14328
in addition, You have 3 while loops and two times where you assign 0
to i
....
Upvotes: 1
Reputation: 393821
You are incrementing i
prematurely, causing an ArrayIndexOutOfBoundsException
. You should increment it after assigning a number of 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 - i.e. i
is incremented after all the other statements of the loop's body.
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++;
}
Upvotes: 6