空心字母金字塔
输入一个大写的英文字母,输出空心的字母金字塔。
输入格式:
一个大写英文字母。
输出格式:
一个空心的大写英文字母金字塔,其中第1层的“A”在第1行的第40列,列从1开始计数。
输入样例:
E
输出样例:
A
B B
C C
D D
EEEEEEEEE
代码
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
//输入字符
char top = input.nextLine().charAt(0);
//计算金字塔的高度,总宽度,以及A所在位置前面的空格数
int Height = top - 'A' + 1;
int Width = 80;
int blank = Width / 2 - 1;
//循环每行
for (int n = 0; n < Height; n++) {
//输出字母前的空格
for (int i = 0; i < blank; i++) {
System.out.print(" ");
}
//输出左侧字母
System.out.print((char)('A' + n));
//输出中间的空格或者字母
for (int i = 0; i < 2 * n - 1; i++) {
//最后一行,输出字母
if (n == Height - 1) {
System.out.print((char)('A' + n));
} else {
System.out.print(" ");//其余行为空格
}
}
//输出右侧字母
if (n > 0) {
System.out.print((char)('A' + n));
}
//输出空格
System.out.println();
//下一行字母前空格减1
blank--;
}
}
}
代码详解
思路
1.字母对应的ACSLLA表
A-Z:65-90
a-z:97-122
0-9:48-57
2.金子塔的高度,也就是A到输入的字母,A:65,E:69,高度就是E-A+1=5;
宽度定为80;
第一行'A'前的空格数为,宽度/2-1,保证A在第四十列
3.遍历每行
空格数依次减少,前移一位;
空格后输出左边字母;
判断是否是最后一行,不是输出相应空格,最后一行输出字母;
输出右边字母;
代码点
charAt(index);
index为0到字符串长度-1;