2017-03-31 31 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++移至循環的結尾,而不是開頭。

相關問題