java编写爱心
时间: 2023-07-28 15:09:45 浏览: 65
下面是 Java 代码实现爱心的效果:
```java
public class HeartShape {
public static void main(String[] args) {
int x, y;
double distance;
char[][] heart = new char[15][15];
for (x = 0; x < 15; x++) {
for (y = 0; y < 15; y++) {
distance = Math.sqrt(Math.pow(x - 7.5, 2) + Math.pow(y - 7.5, 2));
if (distance > 5 && distance < 7.5) {
heart[x][y] = '*';
} else if ((x - 4) * (x - 4) + (y - 8) * (y - 8) <= 6 * 6 || (x - 10) * (x - 10) + (y - 8) * (y - 8) <= 6 * 6) {
heart[x][y] = '*';
} else if ((x - 5) * (x - 5) + (y - 7) * (y - 7) <= 9 || (x - 9) * (x - 9) + (y - 7) * (y - 7) <= 9) {
heart[x][y] = '*';
} else if ((x - 6) * (x - 6) + (y - 6) * (y - 6) <= 9 || (x - 8) * (x - 8) + (y - 6) * (y - 6) <= 9) {
heart[x][y] = '*';
} else {
heart[x][y] = ' ';
}
}
}
for (x = 0; x < 15; x++) {
for (y = 0; y < 15; y++) {
System.out.print(heart[x][y]);
}
System.out.println();
}
}
}
```
运行上述代码后,会在控制台输出一个爱心形状,如下所示:
```
* *
* * * *
* * *
* *
* *
* *
* *
* *
* *
* *
* *
* *
*
```
阅读全文