题目描述
写一个程序从输入文件中去读取四行大写字母(全都是大写的,每行不超过100个字符),然后用柱状图输出每个字符在输入文件中出现的次数。严格地按照输出样例来安排你的输出格式。
输入格式
四行字符,由大写字母组成,每行不超过100个字符
输出格式
由若干行组成,前几行由空格和星号组成,最后一行则是由空格和字母组成的。在任何一行末尾不要打印不需要的多余空格。不要打印任何空行。
输入输出样例
输入 #1
THE QUICK BROWN FOX JUMPED OVER THE LAZY DOG. THIS IS AN EXAMPLE TO TEST FOR YOUR HISTOGRAM PROGRAM. HELLO!
输出 #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
说明/提示
每行输出后面不允许出现多余的空格。
java实现代码如下:
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
int[] wordCounts = new int[26];
Scanner scanner = new Scanner(System.in);
List<String> texts = new ArrayList<>();
String line = "";
int count = 0;
while (count < 4) {
line = scanner.nextLine();
texts.add(line);
count++;
}
String tempStr = "";
char tempChr = ' ';
for (int i = 0; i < texts.size(); i++) {
tempStr = texts.get(i);
for (int j = 0; j < tempStr.length(); j++) {
tempChr = tempStr.charAt(j);
if (tempChr >= 'A' && tempChr <= 'Z') {
wordCounts[tempChr - 'A']++;
}
}
}
int maxRow = 0;
// 比较获得最大的输出行数
for (int i = 0; i < wordCounts.length; i++) {
maxRow = Math.max(wordCounts[i], maxRow);
}
tempStr = "";
List<String> results = new ArrayList<>();
results.add("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");
for (int i = 0; i < maxRow; i++) {
for (int j = 0; j < 26; j++) {
if (wordCounts[j] > 0) {
tempStr += '*';
wordCounts[j]--;
} else {
tempStr += ' ';
}
tempStr += ' ';
}
// 去除末尾多余的空格
results.add((('#' + tempStr).trim()).substring(1));
tempStr = "";
}
for (int i = results.size() - 1; i >= 0; i--) {
System.out.println(results.get(i));
}
}
}