Java 为什么不是';这算元音吗?
我需要计算元音,但这总是返回0Java 为什么不是';这算元音吗?,java,count,Java,Count,我需要计算元音,但这总是返回0 public static int numVowel(String s) { int count = 0,x; for(x = 0; x<s.length();x++) if (x=='a' || x=='e' || x=='i' || x=='o' || x=='u' || x=='A' || x=='E' || x=='I' || x=='O' || x=='U') count++; return count; } publ
public static int numVowel(String s) {
int count = 0,x;
for(x = 0; x<s.length();x++)
if (x=='a' || x=='e' || x=='i' || x=='o' || x=='u' || x=='A' || x=='E' || x=='I' || x=='O' || x=='U')
count++;
return count;
}
publicstaticintnumvowel(字符串s){
整数计数=0,x;
对于(x=0;x,您将计数器/索引与字符文本进行比较
相反,您应该根据这些文字在索引位置检索字符!请参见此处了解如何执行此操作!它应该是s.charAt(x)='a'
而不是x=='a'
。
您应该检查给定索引处的字符。您不想检查x
的值;您想检查x
位置处字符的值。您可以使用s.charAt(x)执行此操作,因为x
是您的索引(而不是s
中的字符)。此外,请始终使用大括号(即使是可选的)
public static int numVowel(String s) {
int count = 0;
for (int i = 0; i < s.length(); i++) {
char x = s.charAt(i);
if (x == 'a' || x == 'e' || x == 'i' || x == 'o' || x == 'u' || x == 'A' || x == 'E' || x == 'I' || x == 'O'
|| x == 'U') {
count++;
}
}
return count;
}
public static int numVowel(String s) {
int count = 0;
for (char ch : s.toLowerCase().toCharArray()) {
if ("aeiou".indexOf(ch) > -1) {
count++;
}
}
return count;
}
或者使用正则表达式从输入的字符串中删除所有非元音的内容,然后返回元音的长度。例如
public static int numVowel(String s) {
return s.toLowerCase().replaceAll("[^aeiou]", "").length();
}
如果您需要多次调用该函数,那么调用String.toLowerCase()
的成本并不是微不足道的;您可以将该正则表达式编译成模式
private static Pattern _PATTERN = Pattern.compile("[^aeiouAEIOU]");
public static int numVowel(String s) {
return _PATTERN.matcher(s).replaceAll("").length();
}
x
只是字符串s
的索引。您必须检索x
位置处的字符,并将其与元音进行比较。您认为x
是什么?它的类型是什么?它是何时设置的?设置的值是什么?