在此代码中,我必须“ n”个字符串。然后计算字符串中的元音数量,并以首先打印具有更多元音的字符串的方式打印“ n”个字符串。

Sample Input:

3
My name
is
Paul Jonas

Sample Output:

Paul Jonas 4
My name 2
is 1


这是我的尝试,但是我无法处理以下输出:具有更多元音的字符串优先出现

import java.util.*;
public class CountVowel {
    public static void  main(String[] args){
        Scanner sc = new Scanner(System.in);
        ArrayList<String> word = new ArrayList<String>();

        int n;
        n = sc.nextInt();

        String str;

        sc.nextLine();
        for(int i=0;i<n;i++){
            str = sc.nextLine();
            word.add(str);
        }

        int arr[] = new int[3];
        int j = 0;
        for(String s:word){
            int count = 0;
            for(int i=0;i<s.length();i++){
                if(s.charAt(i)=='A' || s.charAt(i)=='E' || s.charAt(i)=='I' || s.charAt(i)=='O'||s.charAt(i)=='U'
                || s.charAt(i)=='a' || s.charAt(i)=='e' || s.charAt(i)=='i' || s.charAt(i)=='o' || s.charAt(i)=='u'){

                    count++;

                }
            }
            arr[j] = count;
            j++;

        }

        int i = 0;
        for(String s: word){

            System.out.println(s+" "+arr[i]);
            i++;
        }



    }
}


因此,我没有得到想要的输出。

Input:

3
My name
is
Paul Jonas

Output I'm getting:

My name 2
is 1
Paul Jonas 4

最佳答案

如果不使用类Collections,就无法解决您的任务,首先要定义一个计算单词中元音的方法,如下所示:

private static final String VOWELS = "aeiou";

public static int getCountVowels(String word) {
    int count = 0;
    char[] arr = word.toLowerCase().toCharArray();

    for (char ch: arr) {
        if (VOWELS.indexOf(ch) != -1) { ++count; }
    }

    return count;
}


创建完单词和元音的Map之后,如下所示:

String[] words = {"My name", "is", "Paul Jonas"};
Map<String, Integer> map = new HashMap<>();
for (String word : words) { map.put(word, getCountVowels(word)); }


然后,您必须按相反的值按值对映射条目key,value进行排序,并使用Collections打印它们:

map.entrySet().stream()
    .sorted(Collections.reverseOrder(Map.Entry.comparingByValue()))
    .forEach(entry -> System.out.println(entry.getKey() + " " + entry.getValue()));


在总代码下方打印预期结果:

public class CountVowels {
    private static final String VOWELS = "aeiou";

    public static int getCountVowels(String word) {
        int count = 0;
        char[] arr = word.toLowerCase().toCharArray();
        for (char ch: arr) {
            if (VOWELS.indexOf(ch) != -1) { ++count; }
        }
        return count;
    }

    public static void main(String[] args) {
        String[] words = {"My name", "is", "Paul Jonas"};
        Map<String, Integer> map = new HashMap<>();

        for (String word : words) { map.put(word, getCountVowels(word)); }

        map.entrySet().stream()
           .sorted(Collections.reverseOrder(Map.Entry.comparingByValue()))
           .forEach(entry -> System.out.println(entry.getKey() + " " + entry.getValue()));
    }

}

关于java - 计算元音的数量并以以下方式打印它们:具有更多元音的字符串优先出现,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/62127167/

10-10 13:43
查看更多