【问题标题】:Initialize double array java with enum value用枚举值初始化双数组java
【发布时间】:2014-11-04 13:06:10
【问题描述】:

我有个小问题,希望你能帮帮我:

我在 java 中有一个名为 TOKEN 的类,它里面有这个:

public enum TOKEN { EMPTY, WHITE, BLACK }

在其他类(同一个包)中,我正在尝试创建一个包含列和行的数组矩阵,并且我正在尝试使用其他类“TOKEN”中的值“EMPTY”对其进行初始化:

public class Board {    
private int row;
private int column;
private TOKEN[][] board;

public Board(int nr, int nc){       
    this.row = nr;
    this.column = nc;
    for(int a=0; a < row; a++)
    {
        for(int b=0; b < column; b++)
          board[a][b] = TOKEN.EMPTY;
    }       
}

NR 和 NC 是整数并且具有值(例如 6,7),但是当我尝试运行代码时,它会在此处停止(第一次迭代)

board[a][b] = TOKEN.EMPTY;

有人可以帮助我吗?谢谢!

【问题讨论】:

  • 停止?究竟会发生什么?您可以提供任何错误消息吗?

标签: java arrays enums


【解决方案1】:

你必须先初始化数组:

board = new TOKEN[nr][nc];

【讨论】:

    【解决方案2】:

    您需要先使用new TOKEN[nr][nc] 初始化board 变量:

    public class Board {
        private final int row;
        private final int column;
        private final TOKEN[][] board;
    
        public Board(int nr, int nc) {
            this.row = nr;
            this.column = nc;
            // here we initialize the array, otherwise board will be null
            board = new TOKEN[nr][nc];
            for (int a = 0; a < row; a++) {
                for (int b = 0; b < column; b++) {
                    board[a][b] = TOKEN.EMPTY;
                }
            }
        }
    
        public static void main(String[] args) {
            Board board = new Board(10, 10);
        }
    }
    

    【讨论】:

      【解决方案3】:

      在您的构造函数Board 中,您需要先初始化数组,然后才能用空令牌填充它:

      public Board(int nr, int nc) {
          board = new TOKEN[nr][nc];    // initializes the matrix with nr arrays of nc size
          this.row = nr;
          this.column = nc;
          for (int a = 0; a < row; a++) {
              for (int b = 0; b < column; b++) {
                  board[a][b] = TOKEN.EMPTY;
              }
          }
      }
      

      【讨论】:

        【解决方案4】:

        您已保留收到的错误:NullPointerException。你得到这个异常是因为你忘记了初始化你的数组:

        public Board(int nr, int nc){       
            this.row = nr;
            this.column = nc;
            this.board = new TOKEN[nr][nc]; // <-- here
            for(int a=0; a < row; a++) {
                for(int b=0; b < column; b++)
                board[a][b] = TOKEN.EMPTY;
            }       
        }
        

        【讨论】:

          【解决方案5】:

          缺少初始化:

          ...
          board = new TOKEN[row][column]; // <---
          for(int a=0; a < row; a++)
          ...
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2011-12-31
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2013-06-01
            • 1970-01-01
            • 2011-10-21
            • 1970-01-01
            相关资源
            最近更新 更多