2016-11-10 113 views
-1

我已經創建了一個將字符串值轉換爲新的Double的方法。我想創建一個if語句,用於測試所述方法是否返回它應該執行的null。這是到目前爲止的代碼:如何正確調用轉換爲Double方法的字符串?

內容類

public class Content 
{ 
     Double x; 

String string = "b"; 

     public void testParsing() 
     { 
     if (//call xMethod == null) { 
      System.out.println("Ovalid operator Success");} 
      else { 
        System.out.println("Invalid operator Fail"); 
        } 
     } 

     /* 
     * Chops up input on ' ' then decides whether to add or multiply. 
     * If the string does not contain a valid format returns null. 
     */ 
     public Double x(String x) 
     { 

    String[] parsed; 
    if (x.contains("*")) 
    { 
     // * Is a special character in regex 
     parsed = x.split("\\*"); 

     return Double.parseDouble(parsed[0]) * Double.parseDouble(parsed[1]); 
    } 
    else if (x.contains("+")) 
    { 
     // + is again a special character in regex 
     parsed = x.split("\\+"); 

     return Double.parseDouble(parsed[0]) + Double.parseDouble(parsed[1]); 
    } 

    return null; 
} 
} 

Main類

public class MainClass { 

public static void main(String[] args) { 

Content call = new Content(); 

call.testParsing(); 

} 
} 

我知道以下行編譯和輸出作爲一個成功:(第9行)

if (x("") == null) { 

但我不認爲這是在做我要求它做的事情,我要求它檢查x所指向的方法的結果是否返回null。任何澄清如何正確調用這種方法來檢查這種情況將非常感謝,謝謝。

+0

@ cricket_007:是什麼讓你認爲?你認爲哪個JLS規則被侵犯? –

+0

@JonSkeet該領域將如何區別於該方法? –

+0

Bah,[found this](http://stackoverflow.com/questions/9960560/java-instance-variable-and-method-having-same-name#9960571)。這是愚蠢的... –

回答

0

但我不認爲這是做什麼的,我要求它做

要檢查,如果結果爲空。你的邏輯是正確的。

您可能要儲存的結果,如果你打算以後使用它,但。

Double val = x(""); 
if (val == null) { 
    // Invalid 
} else { 
    System.out.println("Valid! Result: " + val); 
} 
+0

啊好吧謝謝,抱歉打擾。 – John123

相關問題