java为什么每次循环代码后我的计数器都没有上升?
这个程序应该检查您输入的字符串中的元音,然后输出元音的数量。但是,当我运行程序时,计数器显示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);
}
}
# 1 楼答案
这是因为
seq.toUpperCase()
没有做你认为它做的事情。它返回String
的一个副本,转换成大写,但它不改变原始值。(AString
在Java中是不可变的,因此它不能改变它。)试着把那行改成
# 2 楼答案
字符串在Java中是不可变的,所以您不能就地修改它们。当您对字符串调用
toUpperCase()
时,它将返回该字符串的一个副本,其中所有字符都更改为其大写等效字符,但原始字符串保持不变这意味着您必须再次将调用
toUpperCase
的结果分配给您的变量。因此,与其做