【问题标题】:Making a 2D array a property, JAVA使二维数组成为属性,JAVA
【发布时间】: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;
}
}

【问题讨论】:

  • 我猜你必须初始化高度和宽度

标签: java arrays matrix 2d


【解决方案1】:

在构造函数外声明数组,在构造函数中初始化

...
String[][] field;

...
public Sea(int width, int length){
    field = new String[width][length];
     ...
}
...

【讨论】:

    【解决方案2】:

    方法一: 如果它具有预定义的值,则可以在构造函数中填充它,或者如果需要使用这些值直接调用 toStringWithShips() 用户输入。另外,创建一个 getter 方法以通过任何其他方法获取 2D 数组。

    方法 2: 创建 Setter 方法以填充二维数组的值。创建一个 getter 方法来检索这些值。

    【讨论】:

      【解决方案3】:

      如果在 ctor 中给出了 x 和 y 值,那么您可以在那里初始化数组,但我认为它取决于您的应用程序,如果数组肯定会被使用并且您从初始构造中受益,那么我会推荐在 ctor 中进行初始化,如果不是这种情况,我会考虑在 getter 中使用动态初始化

      【讨论】:

        【解决方案4】:

        对象创建的初始化应该通过构造函数本身来完成,所以最好使用构造函数来达到这个目的

        【讨论】:

          【解决方案5】:

          如果我的问题正确,您还可以创建另一个构造函数,它是一个二维字符串数组,如下所示:--

          public Sea(String [][] field){
             this.field = field
          }
          

          但你也可以对你真正想要达到的目标给出更多解释

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2017-09-12
            • 2014-07-01
            • 2012-04-07
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多