我正在编写一个程序,该程序可以计算用户输入的句子中的元音和辅音的数量。我下面的代码计算了元音的数量,但是它给我带来了奇怪的辅音计数。例如,如果我输入“ g”,则辅音计数为10。
import java.util.Scanner;
public class VowelCount{
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
System.out.print("Enter a sentence :");
String sentence = scan.nextLine();
String vowels = "aeiouAEIOU";
int vowelCount = 0;
int consCount = 0;
int i;
for(i = 0; i < sentence.length(); i += 1){
char currentChar = sentence.charAt(i);
int index;
for(index = 0; index < vowels.length(); index += 1){
if(vowels.charAt(index) == (currentChar)){
vowelCount++;
}else if(Character.isLetter(currentChar) && (vowels.charAt(index) == (currentChar))){
consCount++;
}
}
}
System.out.println(consCount);
System.out.println(vowelCount);
}
}
最佳答案
这可行。我也对其进行了改进,请参见vowels.indexOf
(而不是手动迭代)和带有isLetter
(更正了对元音的错误检查)和输出(添加了;
)和i++
的行。
public class VowelCount{
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
System.out.print("Enter a sentence :");
String sentence = scan.nextLine();
String vowels = "aeiouAEIOU";
int vowelCount = 0;
int consCount = 0;
int i;
int length = sentence.length();
for(i = 0; i < length; i ++){
char currentChar = sentence.charAt(i);
if (vowels.indexOf(currentChar)>=0)
vowelCount++;
else if(Character.isLetter(currentChar))
consCount++;
}
System.out.print(consCount+";");
System.out.print(vowelCount);
}
}