【发布时间】:2014-01-31 00:43:52
【问题描述】:
我编写了一个程序来计算输入字符串中元音和辅音的数量:
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”本身是一个辅音时,它应该是一个元音。我在哪里说明这一点?
【问题讨论】:
-
btw:不用在循环中使用 substring(i, i+1) ,您可以简单地使用 phrase.charAt(i) 来遍历字符串中的所有字符。这种方法提高了效率和可读性。
-
如:j = phrase.substring(i); ?
-
其实更像:j = "" + phrase.charAt(i);