-2 java conditional-statements unreachable-statement
我正在编写一个程序,用于识别字符串"xyz"是否在输入String中进行了证明.我创建了一个变量,它使用for循环存储"xyz"的位置,然后将其与之前和之后的字符数进行比较,使用.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!
Run Code Online (Sandbox Code Playgroud)
if ((lengthBeg != lengthEnd)); <----- remove that semicolon
当你在结尾处放一个分号if就像是一个空if块.你的代码相当于
if ((lengthBeg != lengthEnd)) {
// Do nothing
}
{
return false;
}
return true; // Unreachable because we already returned false
Run Code Online (Sandbox Code Playgroud)