2016-04-29 86 views
0

我想在Java中創建一個矩陣。我執行下面的代碼使用Java創建一個矩陣

public class Tester { 

    public static void main(String[] args) { 

     int[][] a = new int[2][0]; 
     a[0][0] = 3; 
     a[1][0] = 5; 
     a[2][0] = 6; 
     int max = 1; 
     for (int x = 0; x < a.length; x++) { 
      for (int b = 0; b < a[x].length; b++) { 
       if (a[x][b] > max) { 
        max = a[x][b]; 
        System.out.println(max); 

       } 

       System.out.println(a[x][b]); 

      } 

     } 

     System.out.println(a[x][b]); 


    } 
} 

當我運行代碼,我得到了以下錯誤:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0 
    at shapes.Tester.main(Tester.java:8) 

我試着不同的方法來糾正代碼,但沒有什麼是有幫助的 你能爲我糾正代碼嗎?

謝謝

+0

它沒有真正意義上創建一個二維矩陣,其中第二維包含沒有維度。決定:一個1維數組,或者每個維度的尺寸至少爲1的2維, – lazary

+0

順便說一下,你的b變量在'for'循環的外部是不可見的 – MGoksu

回答

4

當你實例化一個數組,你給它大小,而不是指數。因此,使用0號索引,你至少需要一個大小爲1

int[][] a = new int[3][1]; 

這將實例化一個3X1「矩陣」,這意味着在第一組括號中的有效索引是0,1和2;而第二組括號的唯一有效索引是0.這看起來像你的代碼所要求的。

public static void main(String[] args) { 

    // When instantiating an array, you give it sizes, not indices 
    int[][] arr = new int[3][1]; 

    // These are all the valid index combinations for this array 
    arr[0][0] = 3; 
    arr[1][0] = 5; 
    arr[2][0] = 6; 

    int max = 1; 

    // To use these variables outside of the loop, you need to 
    // declare them outside the loop. 
    int x = 0; 
    int y = 0; 

    for (; x < arr.length; x++) { 
     for (y = 0; y < arr[x].length; y++) { 
      if (arr[x][y] > max) { 
       max = arr[x][b]; 
       System.out.println(max); 
      } 
      System.out.println(arr[x][y]); 
     } 
    } 

    System.out.println(arr[x][y]); 
} 
+0

now now works,thank you – Ali12

1

您在第一個數組中存儲3個元素。

試試這個int [] [] a = new int [3] [1];