java输出一个会动的空心菱形
时间: 2023-11-21 13:05:42 浏览: 28
以下是使用Java语言输出一个会动的空心菱形的示例代码:
```
public class MovingDiamond {
public static void main(String[] args) {
int size = 10;
int mid = size / 2;
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
if (Math.abs(j - mid) + Math.abs(i - mid) == mid) {
System.out.print("*");
} else {
System.out.print(" ");
}
}
System.out.println();
}
int x = mid, y = mid;
while (true) {
for (int i = 0; i < mid; i++) {
System.out.print("\r");
for (int j = 0; j < size; j++) {
if (Math.abs(j - x) + Math.abs(i - y) == mid) {
System.out.print("*");
} else {
System.out.print(" ");
}
}
try {
Thread.sleep(50);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
for (int i = mid; i < size; i++) {
System.out.print("\r");
for (int j = 0; j < size; j++) {
if (Math.abs(j - x) + Math.abs(i - y) == mid) {
System.out.print("*");
} else {
System.out.print(" ");
}
}
try {
Thread.sleep(50);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
x = size - x - 1;
y = size - y - 1;
}
}
}
```
这段代码首先在控制台中输出一个静态的空心菱形,然后通过while循环使其动起来。循环中通过不断改变菱形的位置,再将其在控制台中输出即可实现菱形的移动效果。
阅读全文