2014-03-04 34 views
2

我已經寫了一些代碼,檢查2個具有x和y值的區間,並檢查它們是否重疊,並且我提出了返回toString方法:返回方法無法解析爲變量

public String toString() { 
    if (isEmpty()) { 
     String result = String.format("Interval: (EMPTY)"); 
    } else { 
     String result = String.format("Interval: [%s, %s]", Double.toString(left), 
       Double.toString(right)); 
    } 
    return result; 
} 

}

我得到錯誤「的結果不能被解析爲變量」,我不知道爲什麼,因爲如果函數返回一個字符串無論哪種方式,這是什麼期望的字符串的返回類型,所以我真的很困惑,不知道我是否錯過了一些愚蠢的東西。

回答

5

您聲明的結果在if語句或else語句塊的範圍內。一旦代碼退出這些塊,您的結果變量就不再處於範圍之內。

要解決它,只需在正確的範圍內聲明的變量:

public String toString() { 

    String result; 

    if (isEmpty()) { 
     result = String.format("Interval: (EMPTY)"); 
    } else { 
     result = String.format("Interval: [%s, %s]", Double.toString(left), 
       Double.toString(right)); 
    } 
    return result; 
} 

或者只是使用return語句在線:

public String toString() { 

    if (isEmpty()) { 
     return String.format("Interval: (EMPTY)"); 
    } else { 
     return String.format("Interval: [%s, %s]", Double.toString(left), 
       Double.toString(right)); 
    } 

} 
+0

啊好吧有道理,沒想到的是,是的,我結束了使用return語句直列但它困擾我至於爲什麼以前的方法不起作用。非常感謝快速回復:) – user3186023

2

這是一個範圍問題。 result變量只在if語句中聲明,也就是說,只有在isEmpty()返回true時才聲明它。爲了解決這個問題,聲明的if-else塊這樣上面的變量:

public String toString() { 
    String result; 
    if (isEmpty()) { 
     result = String.format("Interval: (EMPTY)"); 
    } else { 
     result = String.format("Interval: [%s, %s]", Double.toString(left), 
     Double.toString(right)); 
    } 

    return result; 
}