Java输出字母排成的菱形(字母及行数自定)
时间: 2024-01-03 22:03:34 浏览: 105
好的,以下是Java代码实现:
```java
import java.util.Scanner;
public class Diamond {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("请输入菱形的行数:");
int n = scanner.nextInt();
System.out.print("请输入菱形的字母:");
char c = scanner.next().charAt(0);
int half = (n + 1) / 2; // 计算菱形的上半部分行数
for (int i = 1; i <= half; i++) {
for (int j = 1; j <= half - i; j++) {
System.out.print(" ");
}
for (int j = 1; j <= 2 * i - 1; j++) {
System.out.print(c);
}
System.out.println();
}
for (int i = half + 1; i <= n; i++) {
for (int j = 1; j <= i - half; j++) {
System.out.print(" ");
}
for (int j = 1; j <= 2 * (n - i) + 1; j++) {
System.out.print(c);
}
System.out.println();
}
}
}
```
运行程序后,输入菱形的行数和字母,会输出相应的菱形。例如,输入行数为7,字母为A,输出结果如下:
```
请输入菱形的行数:7
请输入菱形的字母:A
A
AAA
AAAAA
AAAAAAA
AAAAA
AAA
A
```
如果输入行数为偶数,会自动将其转换为比其小1的奇数。
阅读全文