2017-03-31 27 views
-2

我想要做的是用随机数填充20个整数的数组,然后打印出每个整数重复自身的次数。我越来越想打印出的重复次数时的错误...这里是我的代码:打印出一个数字在一个数组中重复的次数(ArrayIndexOutofBoundException)

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

这里的错误代码:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 20 
    at nivel3.exercicio3.main(exercicio3.java:29) 
+0

'新的随机()。整型().limit(20).boxed()。collect(Collectors.toMap(Function.identity(),1,Integer :: sum))'。完成。 –

+0

你明白那个错误是什么意思吗?你看过吗?这是一个非常常见的错误,也是在大多数情况下最容易解决的错误之一。 – Carcigenicate

回答

0

我在这里看到两个问题。

第一个是这对我没有意义。

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

你应该只做“for”。

我看到的第二个问题是行“k ++”应该在“if”之下。记住数组从0开始到大小-1(这意味着你可以从数字[0]到数字[19])访问。

因此,在你的代码,当k = 19时,再次进入到了,那么你添加+1所以K = 20 ..和numeros [20],这将引发ArrayIndexOutOfBoundsException异常

0

numeros[k]之前你是做k++ ,这导致最后一次迭代中的ArrayIndexOutOfBoundsException。将k++移至循环的结尾,而不是开头。

相关问题