我有一个家庭作业,需要计算字符串中的元音。我的程序正在运行,但不会忽略辅音和空格。我在代码中缺少什么?
static void main(String[] args) {
// TODO Auto-generated method stub
boolean stopProgram = false;
while(!stopProgram == true) {
System.out.println("Enter a Word or \"q\" to end the program: "); // prompt the user for input
Scanner wordScanner = new Scanner(System.in);
String word = wordScanner.nextLine();
if(!word.equals("q")) {
String vowels[] = {"a","e","i","o","u","y","A","E","I","O","U","Y"}; //define upper and lower case vowels
int count = 0;
for(int i = 0; i < word.length(); i++) {
if(String.valueOf(word.charAt(i)).equals(vowels[0]) ||
String.valueOf(word.charAt(i)).equals(vowels[1]));
String.valueOf(word.charAt(i)).equals(vowels[2]);
String.valueOf(word.charAt(i)).equals(vowels[3]);
String.valueOf(word.charAt(i)).equals(vowels[4]);
String.valueOf(word.charAt(i)).equals(vowels[5]);
String.valueOf(word.charAt(i)).equals(vowels[6]);
String.valueOf(word.charAt(i)).equals(vowels[7]);
String.valueOf(word.charAt(i)).equals(vowels[8]);
String.valueOf(word.charAt(i)).equals(vowels[9]);
String.valueOf(word.charAt(i)).equals(vowels[10]);
String.valueOf(word.charAt(i)).equals(vowels[11]);
count++;
}
System.out.println(("The Vowel Count is: ") + count);
}
}
}
}
答案 0 :(得分:2)
那是你的if语句:
if(String.valueOf(word.charAt(i)).equals(vowels[0]) ||
String.valueOf(word.charAt(i)).equals(vowels[1]));
你在最后的;
打破了if语句。
之后,有很多语句(结果被忽略)
String.valueOf(word.charAt(i)).equals(vowels[1]));
不再是if语句的一部分。
然后,你会在每次迭代时递增计数 - 无论if,它是否被;
打断。
答案 1 :(得分:-2)
首先你应该让你的代码更清洁:在你的时间之外创建你的元音列表,这样你就不会在每次迭代时创建它,然后使用双循环来运行你的元音选项卡:< / p>
static void main(String[] args) {
// TODO Auto-generated method stub
boolean stopProgram = false;
String vowels[] = {"a","e","i","o","u","y","A","E","I","O","U","Y"}; //define upper and lower case vowels
while(!stopProgram == true) {
System.out.println("Enter a Word or \"q\" to end the program: "); // prompt the user for input
Scanner wordScanner = new Scanner(System.in);
String word = wordScanner.nextLine();
if(!word.equals("q")) {
int count = 0;
for(int i = 0; i < word.length(); i++) {
for(int j = 0; j < 12; ++j){
if(String.valueOf(word.charAt(i)).equals(vowels[j]){
++count;
break;
}
}
}
System.out.println(("The Vowel Count is: ") + count);
}
}
}