Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/12.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 打印出一个数字在数组中重复自身的次数(ArrayIndexOutofBoundException)_Java_Arrays - Fatal编程技术网

Java 打印出一个数字在数组中重复自身的次数(ArrayIndexOutofBoundException)

Java 打印出一个数字在数组中重复自身的次数(ArrayIndexOutofBoundException),java,arrays,Java,Arrays,我要做的是用随机数填充一个由20个整数组成的数组,然后打印出每个整数自身重复的次数。我在打印重复次数时出错。。。这是我的密码: package nivel3; import java.util.Random; public class exercicio3 { public static void main(String[] args) { int[] numeros; int i=0; numeros=new int[20];

我要做的是用随机数填充一个由20个整数组成的数组,然后打印出每个整数自身重复的次数。我在打印重复次数时出错。。。这是我的密码:

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

您正在执行
k++
之前的
numeros[k]
,这导致在上一次迭代中出现
ArrayIndexOutOfBoundsException
。将
k++
移动到循环的末尾而不是开始处。

我在这里看到两个问题

第一,这对我来说毫无意义

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

对于(i=0;i
new Random().ints().limit(20).boxed().collect(Collectors.toMap(Function.identity(),1,Integer::sum))
.Done。您了解该错误的含义吗?您查找过吗?这是一个非常常见的错误,也是大多数情况下最容易修复的错误之一。
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);