Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何计算字符串中的元音?_Java_String_Count - Fatal编程技术网

Java 如何计算字符串中的元音?

Java 如何计算字符串中的元音?,java,string,count,Java,String,Count,目的是统计用户输入的短语中有多少元音。 用户将输入一个短语,该短语将 my name is nic 本例的输出为 Vowel Count: 4 这是我的代码 import cs1.Keyboard; public class VowelCount { public static void main(String[] args) { System.out.println("Please enter in a sentence."); S

目的是统计用户输入的短语中有多少元音。 用户将输入一个短语,该短语将

my name is nic
本例的输出为

Vowel Count: 4
这是我的代码

    import cs1.Keyboard;
public class VowelCount {

    public static void main(String[] args) {
        System.out.println("Please enter in a sentence.");
            String phrase = Keyboard.readString();
            char[] phraseArray = phrase.toCharArray();
            char[] vowels = new char[4];
            vowels[0] = 'a';
            vowels[1] = 'e';
            vowels[2] = 'i';
            vowels[3] = 'o';
            vowels[4] = 'u';
            int vCount = countVowel(phrase, phraseArray, vowels);
            System.out.println("Vowel Count: " + vCount);
    }

    public static int countVowel(String word, char[] pArray, char[] v) {
        int vowelCount = 0;
        for (int i = 0; i < word.length(); i++) {
            if (v[i] == pArray[i])
                vowelCount++;
        }
        return vowelCount;
    }
}

那么,我如何解决这个问题?有没有比我尝试的方法更好的方法呢?

您尝试在一个四元音数组中存储五个元音

char[] vowels = new char[5]; // not 4.
vowels[0] = 'a'; // 1
vowels[1] = 'e'; // 2
vowels[2] = 'i'; // 3
vowels[3] = 'o'; // 4
vowels[4] = 'u'; // 5
或者

另外,不要忘了调用
toLowerCase()
,否则只计算小写元音

最后,您应该在
pArray
中的每个字符和每个
元音上循环。我想用两个


只需使用正则表达式。这会节省你很多时间

int count = word.replaceAll("[^aeiouAEIOU]","").length();

“^”应该在那里吗?@NicLaQuatra是的。符号
^
表示
'不'
甜蜜!还有,在空的“”之间应该有什么东西吗?它也意味着什么吗?首先,表达式否定非元音。然后计算元音。不过别担心,一切都发生得很快。除了for循环的最后一部分外,所有信息都非常有用。我还没有学会for each循环,哈哈
Vowel Count: 0
char[] vowels = new char[5]; // not 4.
vowels[0] = 'a'; // 1
vowels[1] = 'e'; // 2
vowels[2] = 'i'; // 3
vowels[3] = 'o'; // 4
vowels[4] = 'u'; // 5
char[] vowels = { 'a', 'e', 'i', 'o', 'u' };
for (char ch : pArray) {
  for (vowel : v) {
    if (ch == v) vowelCount++;
  }
}
int count = word.replaceAll("[^aeiouAEIOU]","").length();