自从大学停课后,我就在家里学习java。最近我试着用StdDraw画图,就像你在下面的图片中看到的一样,但是我不明白,为什么中间的红色圆圈不见了,希望你能帮我,谢谢!
one red circle in the middle is missing
导入java.awt.*;
公共类draw1 {
public static void main(String[] args) {
int n = 8;
int width = 300;
int height = 300;
int circle_x = width / n / 2;
int circle_y = height / n / 2;
int radius = 300 / n / 2;
StdDraw.setCanvasSize(width, height);
StdDraw.setXscale(0, 300);
StdDraw.setYscale(0, 300);
StdDraw.setPenRadius(0.002);
StdDraw.setPenColor(Color.blue);
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
if (i == 1 || i == n) {
if (j == 1 || j == n) {
StdDraw.setPenColor(Color.blue);
StdDraw.setPenRadius(0.002);
StdDraw.circle(circle_x, circle_y, radius);
} else if (j >= 2 && j < n) {
StdDraw.setPenColor(Color.red);
StdDraw.setPenRadius(0.006);
StdDraw.circle(circle_x, circle_y, radius);
}
} else {
if (j == 1 || j == n) {
StdDraw.setPenColor(Color.blue);
StdDraw.setPenRadius(0.002);
StdDraw.circle(circle_x, circle_y, radius);
} else if (j >= 2 ) {
if (n % 2 == 0) {
if (j == n / 2) {
StdDraw.setPenColor(Color.orange);
StdDraw.setPenRadius(0.006);
StdDraw.circle(circle_x + radius, circle_y, radius);
} else if ( (i == n / 2 ) ){
StdDraw.setPenColor(Color.red);
StdDraw.setPenRadius(0.006);
StdDraw.circle(circle_x, circle_y + radius, radius);
System.out.println(i + "=i");
}
} else if (n % 2 != 0) {
if (j == n / 2 + 1) {
StdDraw.setPenColor(Color.orange);
StdDraw.setPenRadius(0.006);
StdDraw.circle(circle_x, circle_y, radius);
} else if (i == n / 2 + 1) {
StdDraw.setPenColor(Color.orange);
StdDraw.setPenRadius(0.006);
StdDraw.circle(circle_x, circle_y, radius);
}
}
}
}
System.out.println(j);
circle_x = circle_x + (radius * 2);
}
circle_x = width / n / 2;
circle_y = circle_y + width / n;
}
}
}发布于 2020-04-06 22:31:51
我想这可能是你的问题。
if (n % 2 == 0) {
if (j == n / 2) {
StdDraw.setPenColor(Color.orange);
StdDraw.setPenRadius(0.006);
StdDraw.circle(circle_x + radius, circle_y, radius);
} else if ( (i == n / 2 ) ){ <---- HERE MIGHT BE YOUR PROBLEM
StdDraw.setPenColor(Color.red);
StdDraw.setPenRadius(0.006);
StdDraw.circle(circle_x, circle_y + radius, radius);
System.out.println(i + "=i");
}在一种情况下,i和j是相同的值。如果i和j都等于4,则代码将始终进入第一个if (j == n/2),并且不会执行else if...,因此基本上不会绘制您要求的红色圆圈。
顺便说一下:n%2==0检查实际上是无用的,因为您没有更改n的值(它始终是8)。所以你的最后一段代码永远不会被执行:
} else if (n % 2 != 0) {
if (j == n / 2 + 1) {
StdDraw.setPenColor(Color.orange);
StdDraw.setPenRadius(0.006);
StdDraw.circle(circle_x, circle_y, radius);
} else if (i == n / 2 + 1) {
StdDraw.setPenColor(Color.orange);
StdDraw.setPenRadius(0.006);
StdDraw.circle(circle_x, circle_y, radius);
}
}虽然不能保证,但根据您的代码,这可能是原因。
https://stackoverflow.com/questions/61061656
复制相似问题