如果给出两个坐标,我们如何在画布上制作方形图案。
以下函数应该在尺寸为20x16的画布上绘制一个给定坐标(x1,y1),(x3,y3)的正方形 -
public static void main(String[] args) {
DrawMe(20, 16, 16, 14, 8, 14);
}
public static void DrawMe(int yaxis, int xaxis, int x1, int y1, int x3, int y3) {
int l=Math.abs(x3-x1); int l2=l/2;
int x2=x1+l2; int y2=y1+l2;
int x4=x1+l2; int y4=y1-l2;
char [ ] [ ] canvas = new char [xaxis] [yaxis];
for (int x = 0; x < xaxis; x++) {
for (int y = 0; y < yaxis; y++) {
if((y==x1 && x==y1) || (y==x2 && x==y2) || (y==x3 && x==y3) || (y==x4 && x==y4))
//canvas[x][y]='#';
System.out.print('#');
else {
//canvas[x][y]='.';
System.out.print('.');
}
}
System.out.println();
}/
}
但是,代码给了我这样的输出 -
....................
....................
....................
....................
....................
....................
....................
....................
....................
....................
....................
....................
....................
........#.......#...
....................
虽然我想要这样的东西 -
....................
....................
....................
....................
....................
....................
....................
....................
....................
....................
............#.......
..........#####.....
.........#######....
........#########...
.........#######....
我尝试过很多东西,但事实并非如此。有谁能帮我搞清楚吗?这将是一个很好的帮助!
如果问题看起来很愚蠢,请原谅。只是想弄清楚一些基础知识。提前谢谢。
答案 0 :(得分:0)
public class Test {
public static void main(String[] args) {
Test test= new Test();
test.DrawMe(20, 16, 16, 14, 8, 14);
}
/*
* if you want to draw diamond from 2 points on same X-axis,
* this is short solution that i think.
*
* But you want to draw rectangle from 2 diagonal points on any location,
* variables should be changed to float or double for calculating REAL NUMBER,
* and then other math algorithm is needed.
*/
public void DrawMe(int xaxis, int yaxis, int x1, int y1, int x3, int y3) {
int length = Math.abs(x3-x1);
int harfLength = length / 2;
int minX = (x1 > x3) ? x3 : x1;
int maxX = (x1 > x3) ? x1 : x3;
int minY = y1 - harfLength;
for(int y = 0; y < yaxis+1; y++) {
for(int x = 0; x < xaxis+1; x++) {
if(x > minX+(Math.abs(y-minY)) && x < maxX-(Math.abs(y-minY))) {
System.out.print('#');
} else {
System.out.print('.');
}
}
System.out.println();
}
}
}
这就是结果。
.....................
.....................
.....................
.....................
.....................
.....................
.....................
............#........
...........###.......
..........#####......
.........#######.....
..........#####......
...........###.......
............#........
.....................
.....................
.....................