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}. Но как я могу добавлять в новый массив сумму е каждый раз, когда заканчиваю считать, сколько их в каждом слове?




Используйте традиционный цикл за
for (int i = 0; i < names.length; i++) {
....
int lengthOfWord = names[i];
....
newArray[i] = counter;
}
Если вы используете переменную цикла i во внутреннем цикле, измените ее на j или используйте j для вышеуказанного.
Вы можете сделать это с помощью 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, и сохраняем счетчик в соответствующем индексе массива.
Спасибо, сработало. Я изменил (int) daysOfweek на (int) имена
Вы можете использовать Ручей API и собирать результат в массив, а не использовать традиционный цикл for:
public static int[] eStatistics(String[] names) {
Function<String, Integer> countEs = string -> string.length() - string.replace("e", "").length();
return Arrays.stream(names).map(countEs).mapToInt(i -> i).toArray();
}
Чтобы объяснить, что это делает:
String и возвращает Integer. Эта функция подсчитывает количество букв e в строке. Эта функция взята из этот ответ и может быть заменена любой другой реализацией, выполняющей то же самое.Вторая строка выполняет фактическую работу:
Arrays.stream() просто создает Stream из массива.map() преобразует String в Integer, используя функцию из первой строки.mapToInt() преобразует каждый Integer в int. Это необходимо, если вы хотите вернуть int[], а не Integer[].toArray() наконец собрать Stream в массив.
Это можно сделать, используя другую инкрементную переменную stackoverflow.com/questions/43470874/….