首先,我创建了Rectangle类,该类获得了构造函数参数x坐标,y坐标,宽度和高度。之后,我创建了Grid类,在其中可以添加矩形,它将在网格中写入它们。输出应该是这样的:
立即输入:
Grid r = new Grid();
r.add(new Grid(0, 0, 2, 3));
r.add(new Grid(3, 2, 4, 2));
System.out.println(r);
现在输出:
xx
xx
xx
xxxx
xxxx
输出应为:
xx
xx
xx xxxx
xxxx
我应该对我的代码做什么,以便将x,y坐标考虑在内?这是我的“网格”类:
public class Grid {
private Rectangle rectangle;
private ArrayList<Rectangle> rectangles;
public Grid() {
this.rectangles = new ArrayList<>();
}
public void add(Rectangle rectangle) {
int x = rectangle.getXcoordinate();
int y = rectangle.getYcoordinate();
int width = rectangle.getWidth();
int height = rectangle.getHeight();
rectangles.add(new Rectangle(x,y,width,height));
}
public String getTangle() {
StringBuilder sb = new StringBuilder();
for (Rectangle rectangle : rectangles) {
int x = rectangle.getXcoordinate();
int y = rectangle.getYcoordinate();
int width = rectangle.getWidth();
int height= rectangle.getHeight();
int counter = 1;
while (height >= counter) {
int i = 1;
while (i <= width) {
sb.append("x");
i++;
}
sb.append("\n");
counter++;
}
}
return sb.toString();
}
@Override
public String toString() {
return getTangle();
}
}