-2

文字列「xyz」が入力文字列で認証されているかどうかを識別するプログラムを書いています。「xyz」の位置を格納する変数を for ループで作成し、前後の文字数と比較して、.substring() と .length() で int を作成します。奇妙なことに、コードは最初の 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!
4

1 に答える 1

5

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

の最後にセミコロンを置くifと、空のifブロックがあるようなものです。あなたのコードはと同等です

if ((lengthBeg != lengthEnd)) {
    // Do nothing
}
{
    return false;
}
return true; // Unreachable because we already returned false
于 2015-01-14T00:33:37.830 に答える