题目描述
写一个程序从输入文件中去读取四行大写字母(全都是大写的,每行不超过100个字符),然后用柱状图输出每个字符在输入文件中出现的次数。严格地按照输出样例来安排你的输出格式。
输入格式
四行字符,由大写字母组成,每行不超过100个字符
输出格式
由若干行组成,前几行由空格和星号组成,最后一行则是由空格和字母组成的。在任何一行末尾不要打印不需要的多余空格。不要打印任何空行。
本题两个关键点:
1.寻找每个字母的出现个数
2.确定每行“*”的位置
s[str.charAt(j)-'A']++中,将数组中的每一个元素进行不断地重新赋值,以这个值代表对应字母的个数。
s[i] | 5 1 1 2 8 2 3 5 4 1 1 4 4 2 10 3 1 7 4 7 3 1 1 2 2 1 |
字母 | A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
|
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int s[] = new int[26];
int max =0;
for(int i = 0; i < 4 ; i++) {
String str = sc.nextLine();
for(int j = 0 ; j < str.length() ; j ++) {
if(str.charAt(j)>='A' && str.charAt(j)<='Z') {
s[str.charAt(j)-'A']++;//确定每个字母出现的次数
}
}
}
for(int i = 0 ; i <= 25 ; i++) {
max = Math.max(s[i], max);
}
for(int i =max ; i >=1; i--) {
for(int j = 0 ; j <= 25 ; j++) {
if(s[j] >= i) {
System.out.print("* ");
}else {
System.out.print(" ");
}
}
System.out.println();
}
for(int i = 0 ; i < 26 ; i++) {
System.out.printf("%c ",'A'+i);
}
}
}