java - 计算字符串列表中的元音并打印计数

标签 java arrays arraylist

我有一个代码必须仅打印数组列表中字符串中的元音,但我不确定我的方法是否正确。我该如何解决这个问题?它只打印出其中 5 个,因为我不确定如何直接获取每个特定的元音。请找到我尝试过的以下代码。

import java.util.*;

public class vowels {

    public static void main(String[] args) {

        ArrayList<String> vowels = new ArrayList<String>();

        vowels.add("mitsubishi");
        vowels.add("subaru");
        vowels.add("nissan");
        vowels.add("honda");
        vowels.add("toyota");


        averageVowels(vowels);
    }

    public static void averageVowels(ArrayList<String> vowels) {

        System.out.println(vowels);

        int number = 0;

        for (int i = 0; i < vowels.size(); i++)
        {
            if (vowels.get(i).contains("a") || vowels.get(i).contains("e") || vowels.get(i).contains("i") ||vowels.get(i).contains("o") || vowels.get(i).contains("u"))
            {
                number++;
            }
        }
        System.out.println("a count: " +number);
        System.out.println("e count: " +number);
        System.out.println("i count: " +number);
        System.out.println("o count: " +number);
        System.out.println("u count: " +number);
    }
}

最佳答案

你可以在没有任何循环的情况下完成,非常容易

public static void averageVowels(ArrayList<String> vowels) {
    System.out.println(vowels);
    String arrayToString = vowels.toString();
    int length = arrayToString.length();
    System.out.println("a count: " + (length - arrayToString.replace("a", "").length()));
    System.out.println("e count: " + (length - arrayToString.replace("e", "").length()));
    System.out.println("i count: " + (length - arrayToString.replace("i", "").length()));
    System.out.println("o count: " + (length - arrayToString.replace("o", "").length()));
    System.out.println("u count: " + (length - arrayToString.replace("u", "").length()));
}

打印

[mitsubishi, subaru, nissan, honda, toyota]
a count: 4
e count: 0
i count: 4
o count: 3
u count: 3

关于java - 计算字符串列表中的元音并打印计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26436276/

相关文章:

java - 使用基于 sign-post api 的 grails-oauth 插件刷新 Yahoo Oauth 访问 token

javascript - 如何在数组方法链中展开 Promise 数组?

java - Google Appengine 请求 pub sub 时出错

java - 尝试在 android studio 中设置背景时出现错误消息?

java - 在 Java 中使用正则表达式进行分组

javascript - 将长 Jade 数组变量拆分为多行

java - 找到两个数组中的值

java - 在Java中计算样本方差,但在插入相似数字时给出错误的答案

java - 空 arrayList 和空字符串抛出 StringIndexOutOfBounds 异常

java - 静态ArrayList - 填充增强循环