如何计算单词出现在数组中的次数

时间:2014-03-17 20:17:08

标签: java arrays count

我试图计算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();
    }
}

1 个答案:

答案 0 :(得分:8)

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);
        }
    }