Java's weird unreachable code error

174 Views Asked by At

I'm writing a program that identifies whether a String "xyz" is certralized in the input String or not. I create a variable that stores the position of "xyz" with a for loop, and then compare it to the number of chars before and after, creating ints with .substring() and .length(). Strangely enough, the code doesn't compile after the first if - which returns true or false, saying whatever return statement after that is unreachable. Could anyone help me wrap my head around this?

Thanks a lot!

Maybe because the length variables haven't been run yet and, for the compiler, they will always be different? How to solve that?

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

There are 1 best solutions below

0
On

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

When you put a semicolon at the end of an if it is like having an empty if block. Your code is equivalent to

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