我试图使用像三角形这样的形状输出图像,以二维数组打印所有图像。我需要三角类的帮助;
矩形类:
public class Rectangle {
int width;
int height;
int x;
int y;
public Rectangle(int x, int y, int w, int h) {
this.width = w;
this.height = h;
this.x = x;
this.y = y;
}
public void draw(Canvas c) {
for (int i = 0; i <= width; i++) {
for (int j = 0; j <= height; j++) {
c.drawAt('*', i + x, j + y);
}
System.out.println();
}
}
}
主要编程:
public class Senary {
public static void main(String[] args) {
Canvas c = new Canvas(60, 40);
c.fillBackground(' ');
Rectangle r = new Rectangle(2, 2, 2, 2);
Triangle1 t = new Triangle1(10, 10, 5, 4);
r.draw(c);
t.draw(c);
c.drawToScreen();
}
}
Canvas as 2D array:
public class Canvas {
char[][] buffer;
int width;
int height;
public Canvas(int w, int h) {
this.width = w;
this.height = h;
buffer = new char[height][width];
}
public void fillBackground(char c) {
for (int i = 0; i < height; i++) {
for (int j = 0; j < width; j++) {
buffer[i][j] = c;
}
}
}
public void drawAt(char c, int i, int j) {
buffer[j][i] = c;
}
public void drawToScreen() {
for (int i = 0; i < height; i++) {
for (int j = 0; j < width; j++) {
System.out.print(buffer[i][j]);
}
System.out.println();
}
}
}
三角类:
public class Triangle1 {
int base;
int length;
int x;
int y;
public Triangle1(int x, int y, int l, int b) {
this.base = b;
this.length = l;
this.x = x;
this.y = y;
}
public void draw(Canvas c) {
for (int i = 1; i <= length; i++) {
for (int j = base; j >= i; j--) {
System.out.println(" ");
}
for (int k = 1; k <= (2 * i - 1); k++)
c.drawAt('*', i + x, k + y);
}
System.out.println();
}
}
必须通过从构造函数中获取长度,基数,x轴,y轴来打印此三角形。有人可以帮忙吗?
输出应该是: * ****
*** ****
***** ****
******* ****
根据x,y三角形和矩形必须打印!