How to check if an array contains a specific number of values?

Ali Zekaj :
import java.util.Scanner;

public class CountVowel{
    public static void main(String[] args){
        Scanner scan = new Scanner(System.in);

Getting the size of the array:

        System.out.println("Type how many words will be typed: ");
        int input = scan.nextInt();    

Filling array with string values

        String[] ar1 = new String[input];
        for(int i = 0; i < ar1.length; i++){
            System.out.println("Type the elements of array with words: ");
            ar1[i] = scan.next();      
        }

Output of the program :

        System.out.println( input + " words are typed and " + 
        countVowels(ar1) + 
         " of them contain more than 3 vowels.");
    }

The method that counts vowels:

    public static int countVowels(String[] ar1){  // this method counts 

        int a = 0;
        String[] ar2 = new String[]{"a", "e", "i", "u", "y", "o"};
        for(int i = 0; i < ar1.length; i++){
            for(String s : ar2){
                if(ar1[i].toLowerCase().contains(s)){
                    a++;
                }
            }
        }
        return a;
    }
}

The method above is to check the vowels, but i dont know how to make it check if there are more than 3 vowels.

Alan :
public static int countVowels(String[] ar1) { // this method counts

    int vowelPerWord = 0;
    int totalWordsWithThreeVowels = 0;
    char[] ar2 = new char[] { 'a', 'e', 'i', 'u', 'y', 'o' };
    for (int i = 0; i < ar1.length; i++) {
        vowelPerWord = 0;
        for (int j = 0; j < ar1[i].length(); j++) {
            for (int k = 0; k < ar2.length; k++) {
                if (ar2[k] == (ar1[i].charAt(j))) {
                    vowelPerWord++;
                }
            }
        }
        if (vowelPerWord >= 3) {
            totalWordsWithThreeVowels++;
        }
    }
    return totalWordsWithThreeVowels;
}

EDIT

alright now i fixed the error and edited the variablenames to make a bit more sense. although this is O(n*m) i believe (where n is the ammount of strings and m is the ammount of char the longest string has) (not so good complexity) it gets the job done ar1 in this case is your input of strings, ar2 are just the vowels that exist.

so you go through every string in ar1 and set "vowelPerWord" to 0, go through every single char in every string and check if it is a vowel increase the vowelPerWord by 1. at the end, after you went through every char of that string you check if there were 3 or more vowels, if so increase the totalWordsWithThreeVowels, which at the end is returned.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=94211&siteId=1