Java的怪异无法访问的代码错误
问题描述:
我正在编写一个程序,该程序可以识别字符串“xyz”是否在输入字符串中进行了规范化处理。我创建了一个变量,用for循环存储“xyz”的位置,然后将它与前后的字符数进行比较,用.substring()和.length()创建整数。奇怪的是,代码不会在第一次if后返回true或false,并且不能在后面返回语句。 任何人都可以帮我把这个包裹起来吗?Java的怪异无法访问的代码错误
非常感谢!
也许是因为长度变量尚未运行,对于编译器来说,它们将始终不同?如何解决这个问题?
public static boolean xyzCenter(String str){
//identifies the position of "xyz" within the String.
int xyzPosition=1;
//loops through the string to save the position of the fragment in a variable.
for(int i = 0; i<str.length(); ++i){
if(str.length()>i+2 && str.substring(i, i+3).equals("xyz")){
xyzPosition=i;
}
}
//ints that determine the length of what comes before "xyz", and the
length of what comes after.
int lengthBeg = str.substring(0, xyzPosition).length();
int lengthEnd = str.substring(xyzPosition+3, str.length()).length();
if ((lengthBeg != lengthEnd));{
return false;
} //this compiles.
return true; //this doesn't!
答
if ((lengthBeg != lengthEnd)); <----- remove that semicolon
当你把一个分号的if
它就像一个空if
块的结尾。您的代码就相当于
if ((lengthBeg != lengthEnd)) {
// Do nothing
}
{
return false;
}
return true; // Unreachable because we already returned false
如果你能解释一下为什么我会投×最大 –
@KickButtowski完成 –
哎呀,这是正确的!谢谢一堆! –