Java奇怪的无法访问的代码错误

时间:2015-01-14 00:32:31

标签: java conditional-statements unreachable-statement

我正在编写一个程序来识别String" xyz"是否在输入字符串中进行了证明。我创建了一个变量来存储" xyz"的位置。使用for循环,然后将其与之前和之后的字符数进行比较,使用.substring()和.length()创建整数。奇怪的是,代码在第一个if之后没有编译 - 它返回true或false,表示无法访问之后的任何return语句。 任何人都可以帮助我解决这个问题吗?

非常感谢!

也许是因为长度变量还没有运行,对于编译器来说, 他们会永远不同吗?怎么解决?

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!

1 个答案:

答案 0 :(得分:5)

if ((lengthBeg != lengthEnd)); <----- remove that semicolon

当你在if的末尾添加分号时,就像有一个空的if块。您的代码等同于

if ((lengthBeg != lengthEnd)) {
    // Do nothing
}
{
    return false;
}
return true; // Unreachable because we already returned false