【问题标题】:Java's weird unreachable code error [closed]Java奇怪的无法访问的代码错误[关闭]
【发布时间】:2015-01-14 00:32:30
【问题描述】:

我正在编写一个程序来识别字符串“xyz”是否在输入字符串中被认证。我使用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!

【问题讨论】:

    标签: java conditional-statements unreachable-statement


    【解决方案1】:

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-09-23
      • 1970-01-01
      • 2013-02-08
      • 1970-01-01
      • 2011-01-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多