我应该如何将二维数组添加到我的属性和构造函数中。我假设有一个对象 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;
}
}
最佳答案
在构造函数外声明数组,在构造函数中初始化
...
String[][] field;
...
public Sea(int width, int length){
field = new String[width][length];
...
}
...
关于java - 使二维数组成为属性,JAVA,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24020593/