【发布时间】:2014-06-03 16:44:38
【问题描述】:
我想如何将二维数组添加到我的属性和构造函数中。我假设有一个对象 Sea,它是一个二维字符串数组和一个采用 x 和 y 坐标的构造函数。但是我应该在哪里初始化数组。在构造函数中还是在它之外?
package battleship;
public class Sea {
//declare properties
private int width;
private int lenght;
private String[][] field = new String[getLenght()][getWidth()];
public int getWidth() {
return width;
}
public int getLenght() {
return lenght;
}
public String[][] getField() {
return field;
}
//create constructor
public Sea(int width, int length){
this.width = width;
this.lenght = length;
field = new String[length][width];
}
//creates a method that visualizes the field with the ships
String[][] toStringWithShips(){
for(int col = 0; col < this.getLenght(); col++){
for(int row = 0; row < this.getWidth(); row++){
field[col][row] = ".";
}
}
return field;
}
}
【问题讨论】:
-
我猜你必须初始化高度和宽度