2017-04-08 73 views
-1

我得到的錯誤數組索引超出範圍! Java的運行計數

java.lang.ArrayIndexOutOfBoundsException:20

我不知道如果我想有一個while循環或打破它,所以它沒有按」噸超過陣列的長度。我看到其他職位,說明爲什麼發生,但我沒有看到任何顯示如何解決它。請幫忙!

/* 
* To change this license header, choose License Headers in Project Properties. 
* To change this template file, choose Tools | Templates 
* and open the template in the editor. 
*/ 
package secondarray; 
import java.util.Random; 
/** 
* 
* @author iii 
*/ 
public class SecondArray { 

    /** 
    * @param args the command line arguments 
    */ 
    public static void main(String[] args) { 
     Random generator = new Random(); 
     int[]run= new int[20]; 
      for (int i= 0;i<run.length;i++) 
     { 
      run[i]=generator.nextInt(6)+1; 

     } 
      marking(run); 
    } 
    public static void marking(int[] run){ 

     for (int i =0;i<run.length;i++){ 
      while(run[i]<= run[20]){ 

      if(run[i]==run[i-1]&&run[i]==run[i+1]){ 
       System.out.print(run[i]); 
      } 
      if(run[i]!=run[i-1]&&run[i]==run[i+1]){ 
       System.out.print("("+run[i]); 
      } 
      if(run[i]==run[i-1]&& run[i]!=run[i+1]){ 
       System.out.print(run[i]+")"); 
       } 
      if(run[i]!=run[i-1]&& run[i] == run[i+1]){ 
       System.out.print(run[i]); 
       } 

      } 
     } 

    } 

} 
+0

'對(INT I = 0;我<= run.length;我++){'應該是'對(INT I = 0; I < run.length - 1; i ++){'自從您訪問'i + 1'後。你也應該從'i = 1'開始,因爲你也可以訪問'i-1'。 –

+0

你的for(int i = 0; i <= run.length; i ++){'應該是''<='就像它在'for(int i = 0; i

回答

0

你必須改變這一點:

for (int i = 0; i <= run.length; i++){ 

這樣:

for (int i = 0; i < run.length; i++){ 

或者

for (int i = 0; i <= run.length-1; i++){ 

你開始從0循環,所以你應該把你的陣列停止在length-1而不是length您的陣列和指標應該是這樣的:

Values [1, 2, 3, 4, 5, 6] 
Indexes [0, 1, 2, 3, 4, 5] 

編輯

您嘗試比較後續和前值,所以,我認爲你需要做這樣的事情(不需要的while()循環,並確保從1啓動循環和停止lenght -2)這樣(int i = 1; i < run.length - 1; i++),所以你的程序應該是這樣的:

for (int i = 1; i < run.length - 1; i++) { 

    if (run[i] == run[i - 1] && run[i] == run[i + 1]) { 
     System.out.print(run[i]); 
    } 
    if (run[i] != run[i - 1] && run[i] == run[i + 1]) { 
     System.out.print("(" + run[i]); 
    } 
    if (run[i] == run[i - 1] && run[i] != run[i + 1]) { 
     System.out.print(run[i] + ")"); 
    } 
    if (run[i] != run[i - 1] && run[i] == run[i + 1]) { 
     System.out.print(run[i]); 
    } 
} 
+0

我做了這個,現在它只會說run和不輸出任何東西或停止'for(int i = 0; i <= run。(run [i] <= run [run.length -1]){' – zebras0388

+0

檢查我的編輯@ zebras0388,希望這可以幫助你 –

0

您的for (int i =0;i<=run.length;i++){中的<=應該是<,就像它在您的for (int i= 0;i<run.length;i++)中一樣。

此外,在int[20],索引是通過019(含)的,所以你不能使用run[20]這裏:

while(run[i]<= run[20]){ 
// Error ---------^^^^ 

run中的最後一項是run[19]

採取進一步:marking不應該假設它知道多少個條目中有run,所以它真的應該是:

while(run[i]<= run[run.length - 1]){ 
0

的標記方法替換for (int i =0;i<=run.length;i++)
for (int i =0;i<run.length;i++)

因爲任何數組的最後一個索引是長度 - 1