java - 每次统计完出现次数后将结果添加到int数组

标签 java arrays oop counter

public class HelloWorld{
    public static void main(String[] args){
        //create array with days of week. won't be modified
        String[] daysOfWeek = {"Monday","Tuesday", "Wednesday","Thursday","Friday", "Saturday","Sunday"};
        //pass the array to the eStatistics method so they check frequency of e
        eStatistics(daysOfWeek);
    }


    public static int[] eStatistics(String[] names){
        //create new array that will be the same size of the previous array but will have integers
        int[] newArray = new int[names.length];
        //go over each word (element) in the old array
        for(String word : names){
            System.out.println(word);
            //create a counter to store number of e's
            int counter = 0; //counter here so it resets every time we go over a different word
            int lengthOfWord = word.length();
            //go over each letter in the word
            for(int i = 0; i < lengthOfWord ; i++){
                if (word.charAt(i) == 'e'){ //if the letter is an 'e'
                    counter ++; //increment counter by 1
                }
            }
            // we should add the counter to the new array after we end counting the letter e in each word
            // how?
            // newArray[i] = counter;   ????
            System.out.println(counter);
        }
        return newArray;
    }
}

这个程序的目的是统计数组daysOfWeek中每个单词中'e'出现的频率,返回一个数组{0, 1, 2, 0, 0, 0, 0}。但是,每次我计算完每个单词的个数后,如何将 e 的总数添加到新数组中呢?

最佳答案

您可以使用 java-8 这样做,将方法更改为:

public static int[] eStatistics(String[] names) {
    int[] newArray = new int[names.length];

    for (int i = 0; i < names.length; i++) {
        newArray[i] = (int) names[i].chars().filter(ch -> ch == 'e').count();
    }

    return newArray;
}

这里我们检查每个 String 包含字符 e 的次数,并将计数存储在数组的相应索引处。

关于java - 每次统计完出现次数后将结果添加到int数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53766084/

相关文章:

java - 对于Databag中的每个元组一次又一次地从try block 执行

c++ - 如何从 uint8_t 数组中提取不同大小的值?

c++ - 访问C中的数组元素

python - 如何使父类(super class)独有的类属性

java else if.不知道哪里出了问题

java - Android:如何使 fragment 仅在 map 加载完成时出现?

javascript - Google 脚本将文件大小驱动到电子表格 - 文件迭代器不起作用

java - 如何有效地从服务中调用 Spring 存储库方法?

javascript - 对象值在 vue.js 的数组中返回 'Undefined'

java - 如何正确地从 Fragment 返回一个变量?