-2

what I'm trying to do is filling an array of 20 integers with random numbers, and then printing out the number of times each integer repeats itself. I'm getting an error when trying to print out the number of repetitions... Here's my code:

package nivel3;

import java.util.Random;

public class exercicio3 {

    public static void main(String[] args) {
        int[] numeros;
        int i=0;

        numeros=new int[20];

        Random rand=new Random();
        System.out.println("FILLING ARRAY WITH 20 RANDOM INTEGERS (FROM 0-9) \n");
        do {
            for (i=0; i<20; i++) {
                numeros[i]=rand.nextInt(10);
                System.out.printf("position"+i+of numeros[20]: "+numeros[i]+"\n\n");
            }
        } while (i<20);

        System.out.println("--------------------------------------------------------------------- \n");
        System.out.println("SHOWING THE REPEATED POSITIONS (FOR EACH POSITION OF THE ARRAY)\n");

            for(int j=0; j<20; j++) {
                int k=0;
                do {
                    k++;
                    if (numeros[j]==numeros[k]) 
                        System.out.printf("the integer in the ["+j+"] position is equal to the integer in the ["+k+"] position \n");

                }while (k<20);
           }
    }
}

Here's the error code:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 20
    at nivel3.exercicio3.main(exercicio3.java:29)
yogidilip
  • 782
  • 5
  • 18
Rui Bravo
  • 1
  • 1

2 Answers2

0

You are doing k++ before numeros[k], which is causing ArrayIndexOutOfBoundsException on the last iteration. Move k++ to the end of your loop instead of the beginning.

RaminS
  • 2,151
  • 3
  • 19
  • 29
0

I see two problems here.

The first one is that this has no sense for me.

do {
    for (i=0; i<20; i++) {
        numeros[i]=rand.nextInt(10);
        System.out.printf("position"+i+of numeros[20]: "+numeros[i]+"\n\n");
    }
} while (i<20);

You should do only the "for".

The second problem I see is that line "k++" should be under the "if". Remember arrays starts from 0 to size-1 (this means you can access from numeros[0] to numeros[19]).

So in your code, when k = 19, it enters again to the for, then you add +1 so k =20.. and numeros[20] this throws ArrayIndexOutOfBoundsException

Leandro
  • 461
  • 1
  • 8
  • 23