简体   繁体   中英

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?

 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 . 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 - ie 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++;
    }

另外,您有3个while循环和两次将0分配给i ...的地方。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM