这是我到目前为止的内容:

 System.out.println("CONSONANT AND VOWEL COUNTER: Please type a phrase: ");
    String lastPhrase = keyboard.nextLine();

    int countCon = 0;
    int countVow = 0;

    if (lastPhrase.contains("bcdfghjklmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ")) {
        countVow++;
    }
    if (lastPhrase.contains("abcdefghijklmnopqrstuvwxyzABCDEFGHJKLIMNOPQRSTUVWXYZ")) {
        countCon++;
    }
    System.out.println("There are " + countVow + " vowels and " + countCon + " consonants.");

两个值的总和为0。有什么问题?

最佳答案

根据Java文档

字符串contains(CharSequence s)
当且仅当此字符串包含指定的char值序列时,才返回true。

计算元音数量的最简单方法是遍历并检查String对象的每个字符。

String s = "Whatever you want it to be.".toLowercase();
int vowelCount = 0;
for (int i = 0, i < s.length(); ++i) {
    switch(s.charAt(i)) {
        case 'a':
            vowelCount++;
            break;
        case 'e':
            vowelCount++;
            break;
        case 'i':
            vowelCount++;
            break;
        case 'o':
            vowelCount++;
            break;
        case 'u':
            vowelCount++;
            break;
        default:
            // do nothing
    }
}

09-12 05:34