【问题标题】:How to count the number of times a word appears in an array如何计算一个单词在数组中出现的次数
【发布时间】:2014-03-17 20:17:08
【问题描述】:

我正在尝试计算每个单词在 java 中的数组中出现的次数,然后显示它,但我无法弄清楚我是如何使用扫描仪添加到数组中然后尝试查找方法的这将遍历数组并显示每个单词在该数组中出现的次数。

public class Counting {

    static String[] words = new String[3];
    //static int[] aCounts;
    private static int count;

    public static void countTimesWordApperesInArray() {
        int size = words.length;
        for (int i = 0; i < size; i++) {
            int position = i;
            int count = 0;
            for (int j = 0; j < size; j++) {
                String element = words[i];
                if (words[i].contains(element)) {
                    count++;
                }
            }
            System.out.println(words[i] + " " + count);
        }
    }

    public static void main(String[] args) {
        System.out.println("Enter three Words");
        Scanner scanner = new Scanner(System.in);

        String input = scanner.next();

        while (!("-1").equals(input)) {
            words[count] = input;
            count++;
            input = scanner.next();
        }
        //print();
        countDigits();
    }
}

【问题讨论】:

  • 您遇到了什么问题?错误信息?错误的行为?对countDigits 的调用是否应该调用countTimesWordApperesInArray()

标签: java arrays count


【解决方案1】:

words[i].contains(element) 更改为words[j].equals(element)

public static void countTimesWordApperesInArray() {
        int size = words.length;
        for (int i = 0; i < size; i += 1) {
            int count = 0;

            String element = words[i];
            for (int j = 0; j < size; j += 1) {
                if (words[j].equals(element)) {
                    count += 1;
                }
            }
            System.out.println(words[i] + " " + count);
        }
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-09
    • 2012-01-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多