首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使2D数组成为属性,JAVA

使2D数组成为属性,JAVA
EN

Stack Overflow用户
提问于 2014-06-03 16:44:38
回答 5查看 1.2K关注 0票数 1

如何支持将2D数组添加到属性和构造函数中。我支持有一个object,它是一个二维String数组,一个构造函数,它接受x和y坐标。但是,我在哪里支持初始化数组。在构造函数中还是在构造函数之外?

代码语言:javascript
复制
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;
}
}
EN

回答 5

Stack Overflow用户

回答已采纳

发布于 2014-06-03 16:50:07

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

代码语言:javascript
复制
...
String[][] field;

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

Stack Overflow用户

发布于 2014-06-03 16:51:19

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

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

票数 1
EN

Stack Overflow用户

发布于 2014-06-03 16:53:43

如果x和y值是在ctor中给出的,那么您可以在那里插入数组,但我认为它依赖于您的应用程序,如果数组肯定会被使用,并且您可以从最初的构造中受益,那么我建议您在ctor中初始化,如果它不是,我会考虑在getter中有一个动态init。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/24020593

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档