[英]What's wrong with my if-else statement?
我制作了這個簡單的GUI程序,用於計算特定字符序列的元音和輔音。 計數器還可以,但我遇到if-else語句的問題,當該字符既不是元音也不是輔音時我必須顯示一條消息......這是代碼:
//I initialized these variables:
public static int vowels = 0, consonants = 0, charac = 0;
public static String outputStr;
public static String conso = "bcdfghjklmnpqrstvwxyz";
public static String vow = "aeiou";
//Here's the code for my "count" button
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
String userInput = jTextField1.getText();
userInput = userInput.toUpperCase();
conso = conso.toUpperCase();
vow = vow.toUpperCase();
String wordInput[] = userInput.split("");
vowels = 0;
consonants = 0;
charac = 0;
for(int i=0; i<wordInput.length; i++) {
for(int j=0; j<5; j++) {
char v = vow.charAt(j);
String VL = Character.toString(v);
if(VL.equals(wordInput[i])) {
vowels ++;
charac = 0;}
else {
charac += 1; }
}
for(int h=0; h<21; h++) {
char c = conso.charAt(h);
String CL = Character.toString(c);
if(CL.equals(wordInput[i])) {
consonants ++;
charac = 0; }
else {
charac += 1; }
}
}
String totalVow = Integer.toString(vowels);
String totalCons = Integer.toString(consonants);
jLabel5.setText(totalVow);
jLabel6.setText(totalCons);
//here's the if-else statement:
if (charac == 0) {
jLabel7.setText(" ");
}
else if (charac >= 1) {
jLabel7.setText("The sequence contains invalid characters.");
}
if (userInput.isEmpty()) {
jLabel7.setText("No input.");
}
}
這是它的樣子:
我輸入了一個沒有任何特殊字符或數字的“序列”字符。 但它仍然顯示消息,其中除了元音和輔音之外還有其他字符。 if-else語句有問題嗎? 謝謝您的幫助 :)
問題出在內部for循環中。 每個角色都用5個不同元音中的每一個進行測試,所以它肯定無法匹配至少4個元音,並且charac
將會增加
for(int j=0; j<5; j++) {
char v = vow.charAt(j);
String VL = Character.toString(v);
if(VL.equals(wordInput[i])) {
vowels ++;
charac = 0;}
else {
charac += 1;
}
}
相反,您可以使用String.contains()方法代替內部循環。
你把不相關的代碼放在你的循環中。 你的循環應該像:
for(int i=0; i<wordInput.length; i++) {
char ch=wordInput.charAt(i);
if(Character.isLetter(ch)){
if(isVowel(ch)){// make a method which return true if char is vowel.
vowel++;
}
else{
consonent++;
}
}
}
你在兩個循環中添加了charac
:一個查找輔音,一個查找元音。 你想在這里使用if / else-if / else,其中只有當一個字符不是你添加到charac
的輔音或元音時。
另外,看看番石榴實用程序。 例如,這是你獲得所有元音和所有輔音的方式:
String vowels = "aeiou";
String consonants = "bcdfghjklmnpqrstvwxz";
String input = "mary had a little lamb";
String allVowels = CharMatcher.anyOf(vowels).retainFrom(input);
String allConsonants = CharMatcher.anyOf(consonants).retainFrom(input);
你錯誤地計算無效字符的邏輯。 你所做的是:每當角色不是你剛剛測試的角色時,你就增加計數器,也就是說,對於輸入中的每個角色, charac
變量增加了25倍! 但是,下次角色與當前測試的元音或輔音匹配時,您將charac
變量重置為0!
您可以使用內置String方法來檢查當前字符是元音或輔音之一,例如indexOf
,而不是使用兩個for
循環來單獨檢查每個元音和輔音。 這樣,每個檢查都減少到一個if語句,這使得當它既不是元音也不是輔音時更容易產生“其他”情況。
for (int i = 0; i < userInput.length(); i++) {
char c = userInput.charAt(i);
if (vow.indexOf(c) != -1) {
vowels++;
} else if (conso.indexOf(c) != -1) {
consonants++;
} else {
charac++; // invalid character
}
}
另請注意,您可以使用charAt
方法,而不是將字符串拆分為字符串數組。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.