gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:45:56 28 4
gpt4 key购买 nike

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/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com