java - 使二维数组成为属性,JAVA

标签 java arrays matrix 2d

我应该如何将二维数组添加到我的属性和构造函数中。我假设有一个对象 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/

相关文章:

java - 大写和修剪字符串的注释

java - 灰熊队 Jersey : Getting MessageBodyWriter not found for media type=application/json

java - 将文本转换为二维数组

javascript - 基于分组使用源对象数组的属性创建对象数组

ruby - 在二维数组中注入(inject)增量计数器

matlab - 在 MATLAB 中获取矩阵列最大值的索引

c++ - 从 Eigen 中的矩阵中提取 vector 的正确方法是什么?

java - 如何在JPA中生成sql?

java - GC(分配失败)VS OutOfMemoryError异常

arrays - 将字符串拆分为数组的最佳方法