该程序应该检查您输入的字符串中的元音,然后输出元音的数量。但是,当我运行该程序时,计数器显示 0。Eclipse 没有显示任何错误。
我希望如果我输入hello
然后它会显示2
,但总是显示 0
.
import javax.swing.*;
public class Lab5 {
public static boolean isVowel(char x) {
if (x == 'A' || x == 'E' || x == 'I' || x == 'O' || x == 'U') {
return true;
}
else {
return false;
}
}
public static void main(String[] args) {
String seq;
boolean vowel;
int counter = 0;
seq = JOptionPane.showInputDialog(null, "Please enter a sequence of characters: ");
seq.toUpperCase();
for (int i=0; i<seq.length(); i++) {
vowel = isVowel(seq.charAt(i));
if (vowel == true) {
counter++;
}
}
JOptionPane.showMessageDialog(null, "The number of vowels in your sequence of characters is : " + counter);
}
}
最佳答案
这是因为 seq.toUpperCase()
并没有按照您的想法进行操作。它返回String
的副本,转换为大写,但不会改变原始内容。 (String
在 Java 中是不可变的,因此无法更改它。)
尝试将该行更改为
seq = seq.toUpperCase();
关于java - 为什么我的计数器在每次循环执行代码后没有增加?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26208346/