user10350176:
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;
}
}
このプログラムの目的は、頻度をカウントすることで'e'
、アレイ内のすべての単語にdaysOfWeek
、配列を返します{0, 1, 2, 0, 0, 0, 0}
。しかし、どのように私は新しい配列に各単語にありますどのように多くのたびにI仕上げカウントをEの合計を追加することができますか?
ニコラスK:
あなたは、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;
}
ここでは、それぞれの回数をチェックする文字列の文字を持っているe
と、配列の対応するインデックスの数を格納します。