【问题标题】:How to create/move multiple objects on a 2d array at once?如何一次在二维数组上创建/移动多个对象?
【发布时间】:2014-03-11 14:00:23
【问题描述】:

我们正在尝试创建一个形状并将其放置在基于 2d 控制台的板上。形状将由二维数组上的多个点组成。因此,例如一个三角形看起来像这样是用户输入 4x3x3...

   1
 1 1 1
1 1 1 1

形状将能够移动和增长/缩小。我们已经拥有能够显示其尺寸的形状,以及制作的电路板本身。但实际上将它们放在板上并移动它们(所有点作为一个整体)被证明是困难的。有什么建议么?到目前为止,这是我们的代码...

板代码...

public class Board {

private int size;

public Board(int boardSize){
    this.size = boardSize;
}

public String toString() {

    Playable[][] grid = new Playable [getSize()][getSize()];

    int k = 1;
    while (k <= (grid.length+2)) {
        System.out.print('-');
        k++;
    }

    System.out.println();

    for (Playable[] row : grid) {
        System.out.print("|");
        for (Playable item : row) {
            System.out.print((item == null ? " " : item));
        } System.out.print("| \n");
    }

    k = 1;
    while (k <= (grid.length+2)) {
        System.out.print('-');
        k++;
    }
    return "";
}

public int getSize() {
    return size;
}

public void setSize(int size) {
    this.size = size;
}
 }

形状代码...

 public class Rectangle extends Quads implements Playable {

public Rectangle(int numberOfSides, int numberOfDimensions) {
    super(4, 2);
    // TODO Auto-generated constructor stub
}

public double calcPerimeter() {
    return ((this.getDimensions()[0] + this.getDimensions()[1]) * 2);
}

public double calcArea() {
    double area;
    area = this.getDimensions()[0] * this.getDimensions()[1];
    return area;
}

public String showDimensions() {
    String display = "";
    display += "For this " + this.getColor() + " "
            + this.getClass().getSimpleName() + ": \n";

    display += this.getDIMENSION_LABELS()[0] + ": "
            + this.getDimensions()[0] + "\n";
    display += this.getDIMENSION_LABELS()[1] + ": "
            + this.getDimensions()[1] + "\n";
    display += this.getDIMENSION_LABELS()[2] + ": "
            + this.getDimensions()[0] + "\n";
    display += this.getDIMENSION_LABELS()[3] + ": "
            + this.getDimensions()[1] + "\n";
    display += "The perimeter is " + this.calcPerimeter() + ", \n";
    display += "The area is " + this.calcArea() + ", \n";
    display += "And the seniority is " + this.getSeniority() + "\n";
    return display;
}

【问题讨论】:

    标签: java arrays object console 2d


    【解决方案1】:

    您在每次打印时定义新网格,将 Playable[][] grid 作为字段,这样您就可以存储状态然后这样做

    grid[0][0] = new Playable(){...};//create
    grid[1][0] = grid[0][0];//copy to new location
    grid[0][0] = null; //remove from old location
    

    【讨论】:

    • 您对创建(可播放)主体的期望是什么?我知道你在这里做什么,但不确定你希望我做什么。
    • 我已经完成了可玩匿名,只是为了让您知道应该有一些实现。你已经有了 Rectangle 和 Quads,所以我想你会期望该接口有更多的实现。
    猜你喜欢
    • 2021-03-16
    • 1970-01-01
    • 2020-05-15
    • 1970-01-01
    • 2022-01-02
    • 2014-08-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多