Añadir a consecuencia int matriz cada vez que termine de contar el suceso

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

El propósito de este programa es para contar la frecuencia de 'e'cada palabra en la matriz daysOfWeeky devolver una matriz {0, 1, 2, 0, 0, 0, 0}. Pero ¿cómo puedo añadir el total de correo de la nueva matriz cada vez que el conteo termino cuántos hay en cada palabra?

Nicholas K:

Puede hacerlo a través de java-8, cambie el método a:

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

Aquí, comprobamos el número de veces que cada cadena tiene el carácter ey almacenar la cuenta en el índice correspondiente de la matriz.

Supongo que te gusta

Origin http://43.154.161.224:23101/article/api/json?id=215575&siteId=1
Recomendado
Clasificación