我做了一個程序來算元音和輔音的輸入的字符串數量:計數元音與輔音
Scanner in = new Scanner(System.in);
System.out.print("Enter a string ");
String phrase = in.nextLine();
int i, length, vowels = 0;
int consonants = 0;
boolean y = false;
String j;
length = phrase.length();
for (i = 0; i < length; i++)
{
j = "" + phrase.charAt(i);
boolean isAVowel = "aeiou".contains(j.toLowerCase());
boolean y = "y".contains(j.toLowerCase());
if(isAVowel){
vowels++;
}else if(isAVowel && y){
vowels++;
consonants++;
//}else if(y && !(isAVowel)){
// vowels++;
}else{
consonants++;
}
System.out.println("The number of vowels in \"" +phrase+"\" is "+ vowels+".\n\nThe number of consonants is "+consonants+".\n\n");
當「Y」是它本身說,它的輔音,它應該是一個元音。我在哪裏說這個?
順便說一句元音的數量:代替使用子串( i,i + 1),您可以簡單地使用phrase.charAt(i)遍歷字符串中的所有字符。這種方法提高了效率和可讀性。 – mweisz
so like: j = phrase.substring(i); ? – MrAwesome8
其實更像是:j =「」+ phrase.charAt(i); – mweisz