帮我写一段Java代码显示爱心的
时间: 2023-09-26 08:06:58 浏览: 104
### 回答1:
这是一段用Java代码显示爱心的示例:
```
public class Heart {
public static void main(String[] args) {
System.out.println(" *** ");
System.out.println(" ******* ");
System.out.println(" ** ** ");
System.out.println("** **");
System.out.println("** **");
System.out.println(" ** ** ");
System.out.println(" ******* ");
System.out.println(" *** ");
}
}
```
运行这段代码,控制台就会显示一个爱心。
### 回答2:
当然可以!以下是一个简单的Java代码段,可以显示出一个爱心形状:
```java
public class LoveHeart {
public static void main(String[] args) {
int heartSize = 10;
for (int row = heartSize / 2; row <= heartSize; row += 2) {
for (int space = 1; space < heartSize - row; space += 2) {
System.out.print(" ");
}
for (int star = 1; star <= row; star++) {
System.out.print("*");
}
for (int space = 1; space <= heartSize - row; space++) {
System.out.print(" ");
}
for (int space = 1; space <= row; space++) {
System.out.print(" ");
}
for (int star = 1; star <= row; star++) {
System.out.print("*");
}
System.out.println();
}
for (int row = heartSize; row >= 1; row--) {
for (int space = 0; space < heartSize - row; space++) {
System.out.print(" ");
}
for (int star = 1; star <= row; star++) {
System.out.print("*");
}
for (int space = 1; space <= (heartSize - row) * 2; space++) {
System.out.print(" ");
}
for (int star = 1; star <= row; star++) {
System.out.print("*");
}
System.out.println();
}
}
}
```
运行以上代码将会在控制台输出一个爱心形状,具体的爱心大小可以通过调整`heartSize`变量的值来改变。该代码使用了嵌套的循环和条件语句,通过控制星号和空格的输出位置,形成了一个爱心的形状。
### 回答3:
下面是一个用 Java 代码显示爱心的例子:
```java
public class HeartShape {
public static void main(String[] args) {
int size = 10;
for (int i = size / 2; i <= size; i += 2) {
for (int j = 1; j < size - i; j += 2) {
System.out.print(" ");
}
for (int j = 1; j <= i; j++) {
System.out.print("*");
}
for (int j = 1; j <= size - i; j++) {
System.out.print(" ");
}
for (int j = 1; j <= i; j++) {
System.out.print("*");
}
System.out.println();
}
for (int i = size; i >= 1; i -= 2) {
for (int j = 1; j < size - i; j += 2) {
System.out.print(" ");
}
for (int j = 1; j <= i; j++) {
System.out.print("*");
}
for (int j = 1; j <= size - i; j++) {
System.out.print(" ");
}
for (int j = 1; j <= i; j++) {
System.out.print("*");
}
System.out.println();
}
}
}
```
上述代码使用了星号字符(`*`)来绘制爱心形状。通过循环和条件语句,按照一定的规律打印出一系列星号字符,最终形成了一个爱心的形状。请将代码复制到 Java IDE 中运行查看效果。
阅读全文