1

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);

    }
1
  • 1
    What does the output give you? What were you expecting instead? I know this problem is simple but it's good to be specific and say exactly what the problem is. Commented Apr 19, 2016 at 13:18

2 Answers 2

6

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++;
    }
Sign up to request clarification or add additional context in comments.

Comments

1

in addition, You have 3 while loops and two times where you assign 0 to i ....

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.