Domanda

I try to use this method for create random numbers and save that random number in a array

int[] ndigitos = new int[313];
public int  Imagenes(int cont) {


    do {

        nuevo = r.nextInt(313);

        for (int i = 0; i < total; i++) {

            if (nuevo == ndigitos[i])
                aux = 1;
        }

        if (aux == 0) {
            // agregar en la siguiente posicion el nuevo numero
            ndigitos[total] = nuevo;
            total++;
        }

        aux = 0;
    } while (total < 313);

    return ndigitos[cont];

}

but i have this error when run my app

java.lang.ArrayIndexOutOfBoundsException: length=313; index=313
at com.goldapp.imagenesparawhatsapp.Metodos.Imagenes(Metodos.java:97)
at com.goldapp.imagenesparawhatsapp.Main.onClick(Main.java:139)
at android.view.View.performClick(View.java:4091)
at android.view.View$PerformClick.run(View.java:17072)
at android.os.Handler.handleCallback(Handler.java:615)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:153)
at android.app.ActivityThread.main(ActivityThread.java:5042)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:821)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:584)
at dalvik.system.NativeStart.main(Native Method)
È stato utile?

Soluzione

try to modify your while condition to be (total < 312)

Altri suggerimenti

The length of the array is 313, from the error message you are passing an index that is 313, but you can only access up to 312, since the array starts with a 0 and not a 1.

So from what I see, your error can come from two places, this line:

ndigitos[total] = nuevo;

or this line:

ndigitos[cont];

I cannot see where you are declaring and setting the initial value of total, you can probably find the problem there. Or check what value you are passing as a parameter cont, it might be 313

Hope it helps

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top