Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 使用随机整数的ArrayIndexOutOfBoundsException_Java_Arrays_Random_While Loop_Integer - Fatal编程技术网

Java 使用随机整数的ArrayIndexOutOfBoundsException

Java 使用随机整数的ArrayIndexOutOfBoundsException,java,arrays,random,while-loop,integer,Java,Arrays,Random,While Loop,Integer,我尝试使用此方法创建随机数,并将该随机数保存在数组中 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;

我尝试使用此方法创建随机数,并将该随机数保存在数组中

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

}

尝试将while条件修改为(total<312)

从错误消息中,数组的长度是313,您传递的索引是313,但您最多只能访问312,因为数组以0而不是1开头

从我看来,你的错误可能来自两个地方,这一行:

ndigitos[cont];
ndigitos[total]=nuevo

或此行:

ndigitos[cont];
我看不到您在哪里声明和设置total的初始值,您可能会在那里发现问题。 或者检查作为参数cont传递的值,它可能是313


希望它能有所帮助

您将超过数组末尾1-数组长度为313,您正在访问索引313-您只能合法访问[0312]。我不知道它在哪里,因为你的很多变量都是在别处设置的,比如cont和total,我认为这不是错误的原因,因为total的最后一个变量