Java 打印出一个数字在数组中重复自身的次数(ArrayIndexOutofBoundException)
我要做的是用随机数填充一个由20个整数组成的数组,然后打印出每个整数自身重复的次数。我在打印重复次数时出错。。。这是我的密码: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];
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;inew 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);