我是编程的初学者,我正在编写一个Java方法来删除字符串中的元音,但我不知道如何解决这个错误:";" expected
:
public String disemvowel(String s) {
boolean isVowel(char c);
if (c == 'a') {
return true;
} else if if (c == 'e') {
return true;
} else if if (c == 'i') {
return true;
} else if if (c == 'o') {
return true;
} else if if (c == 'u') {
return true;
}
String notVowel = "";
int l = s.length();
for (int z = 0; z <= l; z++) {
if (isVowel == "false") {
char x = s.charAt(z);
notVowel = notVowel + x;
}
}
return notVowel;
}
答案 0 :(得分:14)
String str= "Your String";
str= str.replaceAll("[AEIOUaeiou]", "");
System.out.println(str);
答案 1 :(得分:6)
更简单的方法是执行以下操作:
String string = "A really COOL string";
string = string.replaceAll("[AaEeIiOoUu]", "");
System.out.println(string);
这会将正则表达式[AaEeIiOoUu]
应用于string
。此表达式将匹配字符组[AaEeIiOoUu]
中的所有元音,并将其替换为""
空字符串。
答案 2 :(得分:1)
你有很多的语法错误。
boolean isVowel(char c);
- 不确定你在做什么。如果你想把它作为一个单独的方法,把它分开(并且不要在它后面放一个分号,这将是无效的语法。
else if if
语法无效。如果你正在进行else if
,那么你只需要一个if
。
for (int z = 0; z <= l; z++)
也会导致您退出字符串。移除<=
,转而使用<
。isVowel == "false"
永远无法运作。您将String与布尔值进行比较。您想要!isVowel
代替。将语法错误放在一边,可以这样想。
有趣的是,你在那里的半方法可以完成确定某些东西是否是元音的逻辑。将其解压缩到自己的方法。然后,在您的其他方法中将其称为。但是请考虑大写字母。
我把剩下的作为练习留给读者。
答案 3 :(得分:1)
这是你的代码,不改变任何逻辑,但解读了isVowel方法:
public String disemvowel(String s) {
// Removed the "isVowel" method from here and moved it below
String notVowel = "";
int l = s.length();
for (int z = 0; z <= l; z++) {
// Note that the "isVowel" method has not been called.
// And note that, when called, isVowel returns a boolean, not a String.
// (And note that, as a general rule, you should not compare strings with "==".)
// So this area needs a lot of work, but we'll start with this
boolean itIsAVowel = isVowel(s.charAt(z));
// (I made the variable name "itIsAVowel" to emphasize that it's name has nothing to do with the method name.
// You can make it "isVowel" -- the same as the method -- but that does not in any way change the function.)
// Now take it from there...
if (isVowel == "false") {
char x = s.charAt(z);
notVowel = notVowel + x;
}
}
return notVowel;
}
// You had this line ending with ";"
boolean isVowel(char c) {
if (c == 'a') {
return true;
// Note that you coded "if if" on the lines below -- there should be only one "if" per line, not two
} else if if (c == 'e') {
return true;
} else if if (c == 'i') {
return true;
} else if if (c == 'o') {
return true;
} else if if (c == 'u') {
return true;
}
// You were missing this final return
return false;
}
(是的,我知道这应该是评论,但你不能将格式化的代码放在评论中。)
答案 4 :(得分:0)
您可以尝试这样的事情:
public static String removeVowels(final String string){
final String vowels = "AaEeIiOoUu";
final StringBuilder builder = new StringBuilder();
for(final char c : string.toCharArray())
if(vowels.indexOf(c) < 0)
builder.append(c);
return builder.toString();
}