2D数组仍然为空

时间:2019-04-09 06:49:47

标签: java object multidimensional-array

我在Board类中有一个2D数组,用于托管Ship类型的对象。 Board类的构造函数使用ship对象启动2D数组,但是当我签出它时,它仍然保持为空。

public class Ship{

    private int tons; // 1 element in 2d array

    public Ship(){
        this.tons=1;
    }

     public Ship(int t){
        this.tons=t;
    }

    public int getTons(){
        return this.tons;
    }

     public void setTons(){
        this.tons = 1;
    }
}
import java.util.Random;

public class Board{

    private Ship battleShip[][];
    private Random rnd=new Random();

    public Board(){
      //setup board with null values
      Ship battleShip[][] = new Ship[5][5]; 

      // initialize
      for (int r=0; r < 5; r++ )
           for (int c=0; c < 5; c++ )
            battleShip[r][c]= new Ship();

    }
}

2 个答案:

答案 0 :(得分:2)

您在构造函数中声明了一个附加变量battleShip。使用您已经在类中定义的类成员变量。

private Ship battleShip[][];//<------------- use this

构造函数应对此进行修改

public Board(){
  //setup board with null values
  battleShip = new Ship[5][5]; //<----------  now member variable is initialed

  // initialize
  for (int r=0; r < 5; r++ )
       for (int c=0; c < 5; c++ )
        battleShip[r][c]= new Ship();

}

答案 1 :(得分:1)

这样做:

public Board(){
      //setup board with null values
      Ship battleShip[][] = new Ship[5][5]; 

阴影类成员battleShip并保留为类中未初始化的字段