如何支持将2D数组添加到属性和构造函数中。我支持有一个object,它是一个二维String数组,一个构造函数,它接受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;
}
}发布于 2014-06-03 16:50:07
在构造函数之外声明数组,在构造函数中初始化它。
...
String[][] field;
...
public Sea(int width, int length){
field = new String[width][length];
...
}
...发布于 2014-06-03 16:51:19
方法1:如果它有预定义的值,则可以在构造函数中填充,或者如果需要使用这些值直接调用toStringWithShips(),则可以填充用户输入。另外,创建一个getter方法来通过任何其他方法获取2D数组。
方法2:创建Setter方法来填充二维数组的值。创建一个getter方法来检索这些值。
发布于 2014-06-03 16:53:43
如果x和y值是在ctor中给出的,那么您可以在那里插入数组,但我认为它依赖于您的应用程序,如果数组肯定会被使用,并且您可以从最初的构造中受益,那么我建议您在ctor中初始化,如果它不是,我会考虑在getter中有一个动态init。
https://stackoverflow.com/questions/24020593
复制相似问题