【问题标题】:multidimensional array in java trying to implement an adjacency matrixjava中的多维数组试图实现邻接矩阵
【发布时间】:2015-11-13 06:40:25
【问题描述】:

我正在尝试使用多维数组来实现邻接矩阵,但是当我编写 for 循环时,我在 Eclipse 中不断出现错误,谁能告诉我我做错了什么。

 public class Graph_arr
            {
              int row  = 6 ;
              int column = 6;
              int [][] member = new int [row][column];
              for(int i=0 ;i < row; i ++)
                  {
                  for (int j = 0 ; j < column ;j++)
                       {
                       member[row][column]= 0;
                       }

                  }             

            }

【问题讨论】:

  • 必须是数组indexoutofbound异常

标签: arrays adjacency-matrix


【解决方案1】:

你会得到 ArrayIndexOutOfBoundException

这是因为您在访问索引 [row][column] 时,您只能合法地访问 0 到 row-1 的行索引和 0 到 column-1 的列索引。

所以,将上述代码中的member[row][column] 更改为member[i][j]

当 i 从 0 移动到 row-1 并且 j 从 0 移动到 column-1 时,不会发生此错误。

【讨论】:

  • 不,它不是 OutOfBounds 异常,在数组实例化时它告诉我语法错误“;”,{ 预期在此令牌之后。
【解决方案2】:

您在循环的每次迭代中为相同的元素赋予值更改循环内的初始化语句

 public class Graph_arr
            {
              int row  = 6 ;
              int column = 6;
              int [][] member = new int [row][column];
              for(int i=0 ;i < row; i ++)
                  {
                  for (int j = 0 ; j < column ;j++)
                       {
                       member[i][j]= 0;
                       }

                  }             

            }

【讨论】:

    猜你喜欢
    • 2017-10-13
    • 2017-07-24
    • 1970-01-01
    • 2014-05-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多