Vertical Histogram
題目:編寫一個程式從輸入檔讀取四行大寫字母組成的文字輸入,並輸出一個垂直柱狀圖顯示在輸入中出現的所有大寫字母(但不包括空格、樓字或標點符號)出現多少次。輸出格式如輸出樣例。
輸入:4行大寫字母的文字。
輸出:第1行到第?行,由星號和空格組成的若干行,後面跟著一行,由被空格分開的大寫字母組成。在任意一行結束時不要輸出不需要的空格,也不要輸出前導空格。
import java.util.Scanner;
public class VerticalHistogram {
public static void main(String[] args) {
char[] letter = { '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' };
int letterCnt[] = new int[letter.length];
int mrow = 4; // 輸入行數
String sentence;
int maxc = 0; // 字母的最高頻率
for (int i = 0; i < mrow; i++) {
Scanner scanIn = new Scanner(System.in); // 輸入資料
sentence = scanIn.nextLine();
for (char c : sentence.toCharArray()) {
for (int j = 0; j < letter.length; j++) {
if (c == letter[j]) {
letterCnt[j]++;
if (letterCnt[j] > maxc) { // 記錄最高頻率的次數
maxc = letterCnt[j];
}
break;
}
}
}
}
System.out.println("");
for (int i = maxc; i > 0; i--) {
for (int j = 0; j < letterCnt.length; j++) {
if (letterCnt[j] >= i) {
System.out.print("* ");
} else {
System.out.print(" ");
}
}
System.out.println("");
}
for (int j = 0; j < letterCnt.length; j++) { // 列印最後一行的大寫字母
System.out.print(letter[j] + " ");
}
}
}
鏈結到這頁!
