2016-04-29 85 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];