2010-07-08 103 views
2

首先,初學者在這裏。我正在使用此代碼。二維陣列幫助

class MDArrays { 
    public static void main(String[] args) { 
     int[][] x; 
     int t=2; 
     x = new int[2][3]; 

     for(int i=0; i<=1; i++) { 
      for(int j=0; i<=2; j++) { 
       x[i][j] = t; 
       t += 2; 
       System.out.println(x[i][j]); 
      } 
     } 
    } 
} 

它編譯完美,但運行時,正確顯示3個數字後,我收到以下錯誤。

Exception in thread "main" java.Lang.ArrayindexOutOfBoundsException : 3 at MDArrays.main(MDArrays.java:13)

我要去哪裏錯了?

+0

+1 - 雖然這是一個簡單的錯誤,但是這個問題有很好的語法,並且寫得很清楚。 – Andres 2010-07-09 20:54:56

回答

8

你正在增加j,同時檢查我。

for(int j=0; i<=2; j++) 

Ĵ將繼續增值,這將最終給你一個IndexOutOfBoundsException異常

+0

不能相信我打錯了它這是一個不好的問題 – MoonStruckHorrors 2010-07-08 16:27:08

3
for(int j=0; i<=2; j++) { 

是你的問題。嘗試:

for(int j=0; j<=2; j++) { 
3

我會寫這樣的:

class MDArrays 
{ 
    private static final int ROWS; 
    private static final int COLS; 
    private static final int START_VALUE; 
    private static final int INC_VALUE; 

    static 
    { 
     ROWS  = 2; 
     COLS  = 3; 
     START_VALUE = 2; 
     INC_VALUE = 2; 
    } 

    public static void main(String[] args) 
    { 
     final int[][] x; 
     int   t; 

     x = new int[ROWS][COLS]; 
     t = START_VALUE; 

     for(int row = 0; row < x.length; row++) 
     { 
      for(int col = 0; col < x[row].length; col++) 
      { 
       x[row][col] = t; 
       t += INC_VALUE; 
       System.out.println(x[row][col]); 
      } 
     } 
    } 
} 

的主要區別是,我使用。長度成員,而不是硬編碼值。這樣,如果我將其更改爲x = new int[3][2];,那麼代碼會神奇地工作並保持在其範圍內。

另一個很大的區別是我使用行/列而不是i/j。我/ j很好(和傳統),但我發現在處理數組數組(Java實際上並沒有多維數組)時,如果我使用更有意義的行/ col(幫助防止你從事for(int col = 0; row < x.length; col++) ......這是你的錯誤,

+0

我也想用私人靜態決賽擺脫那些神奇的數字(2和3) – Joni 2010-07-08 16:41:41

+0

是的,我也打算這樣做,但並不想讓它變得與衆不同 - 但給你也有這種感覺我會這樣做的! – TofuBeer 2010-07-08 16:43:50

+0

你是不是指x.length? Currentl y在行上: for(int row = 0; row 2010-07-08 16:53:34