java – 使用Scanner读取文本文件,并在每个字母出现时计数

所以我有关于数组的任务.要求使用扫描仪读取文本文件并记录每个字母的出现次数并将其存储在表格中.

例如:

public class something {

char[] alphabet = "abcdefghijklmnopqrstuvwxyz".toCharArray();

public void displayTable () {
        for (int i = 0; i < alphabet.length; i++) {
            System.out.println(alphabet[i] + ":  " + count);
        }
    }

我不知道如何构造存储每个字母的出现的方法.

它应该是这样的:

public void countOccurrences (Scanner file) {
     //code to be written here
}

如果文本文件只有一行,则该行为:

Hello World

该方法将忽略任何整数或符号,并仅输出表中出现的char.

d: 1
e: 1
h: 1
l: 3
o: 2
r: 1
w: 1

我无法自己解决这个问题,非常感谢任何帮助!

谢谢,
害羞

最佳答案 只需使用Map.阅读内联评论以获取更多信息.

Map<Character, Integer> treeMap = new TreeMap<Character, Integer>();
// initialize with default value that is zero for all the characters
for (char i = 'a'; i <= 'z'; i++) {
    treeMap.put(i, 0);
}

char[] alphabet = "Hello World".toCharArray();

for (int i = 0; i < alphabet.length; i++) {
    // make it lower case
    char ch = Character.toLowerCase(alphabet[i]);
    // just get the value and update it by one
    // check for characters only
    if (treeMap.containsKey(ch)) {
        treeMap.put(ch, treeMap.get(ch) + 1);
    }
}

// print the count
for (char key : treeMap.keySet()) {
    int count = treeMap.get(key);
    if (count > 0) {
        System.out.println(key + ":" + treeMap.get(key));
    }
}

Hello World忽略大小写的输出

d:1
e:1
h:1
l:3
o:2
r:1
w:1

逐行读取文件.迭代该行的所有字符并更新Map中的事件.

点赞