【问题标题】:Character share in %字符份额百分比
【发布时间】:2018-03-23 17:48:59
【问题描述】:
public static void main(String[] args) throws Exception {
    Map<Character, Integer> characterCounter = new HashMap<Character, Integer>();
    File file = new File("/Users/Downloads/text.txt`enter code here`");
    try(Scanner s = new Scanner(file, "utf-8")){
        while (s.hasNext()) {
            char[] chars = s.nextLine().toLowerCase().toCharArray();
            for (Character c : chars) {
                if(!Character.isLetter(c)){
                    continue;
                }
                else if (characterCounter.containsKey(c)) {
                    characterCounter.put(c, characterCounter.get(c) + 1);
                } else {
                    characterCounter.put(c, 1);
                }
            }
        }
        for (Map.Entry<Character, Integer> countedArray : characterCounter.entrySet()) {
            System.out.println(countedArray.getKey() + ": " + countedArray.getValue());
        }
    }
}

以下代码打印英文字母表中每个字母在给定 txt 文件中出现的次数。现在还好。一切正常。当我运行它时,我得到了 'a' 'b' 等的数量。但是我想实现更多。我希望它显示的不是字母出现的次数,而是它们在文本中的百分比。让我们在文本中说 'a' : 30 % 'b' - 12 % 等。我不确定如何实现这一点。我正在寻找这样做的想法而不是现成的解决方案,因为我觉得它很简单,但我就是无法破解它。

【问题讨论】:

  • 想法:将计数转换为百分比是简单的算术。百分比 = 计数 / 总和(所有计数)* 100。

标签: java arrays string hashmap percentage


【解决方案1】:
public static void main(String[] args) throws Exception {
    Map<Character, Integer> characterCounter = new HashMap<Character, Integer>();
    File file = new File("/Users/Downloads/text.txt`enter code here`");
    int totalCount = 0;
    try(Scanner s = new Scanner(file, "utf-8")){
        while (s.hasNext()) {
            char[] chars = s.nextLine().toLowerCase().toCharArray();
            for (Character c : chars) {
                totalCount = totalCount + 1;
                if(!Character.isLetter(c)){
                    continue;
                }
                else if (characterCounter.containsKey(c)) {
                    characterCounter.put(c, characterCounter.get(c) + 1);
                } else {
                    characterCounter.put(c, 1);
                }
            }
        }
        for (Map.Entry<Character, Integer> countedArray : characterCounter.entrySet()) {
            System.out.println(countedArray.getKey() + ": " + countedArray.getValue() + " - " + ((double) countedArray.getValue()/ (double) totalCount));        }
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-11
    • 1970-01-01
    相关资源
    最近更新 更多