2014-05-05 39 views
-3

請爲這個聰明或stupid..i試圖在一個double類型的方法返回一個字符串..我試圖解析String intto Double,可以嗎?

public double withdrawCash() 
{ 
    if (amounts == 20) 
    { 
     totalWithdrawal = BALANCE - 20; 
     return totalWithdrawal; 
    }else if (amounts == 40){ 
     totalWithdrawal = BALANCE - 40; 
     return totalWithdrawal; 
    }else if (amounts == 60){ 
     totalWithdrawal = BALANCE - 60; 
     return totalWithdrawal; 
    }else if (amounts == 100){ 
     totalWithdrawal = BALANCE - 100; 
     return totalWithdrawal; 
    }else if (amounts == 200){ 
     totalWithdrawal = BALANCE - 200; 
     return totalWithdrawal; 
    } 
    else{ //this where i tried to be smart or stupid...just learning..help!!! 
     String complainWithdrawal = "Please, you need to select appropriate amount"; 
     double showWithdrawal = Double.parseDouble(complainWithdrawal); 
     return showWithdrawal; 
    } 
} 

請諮詢我的理想解決方案

+1

您不能從表示返回double的方法返回字符串。這將使編程成爲一場噩夢。你可以拋出異常。那說'金額'從哪裏來? –

+0

您不能將'String'作爲'double'返回。在我看來,你需要拋出一個異常,以防''量'不是你的期望值之一。 – Mureinik

+0

是的,你是對的。感謝您的建議。 – Progzilla

回答

0
String bla = "12.25"; 

    double showWithdrawal = 0; 

    try { 
     showWithdrawal = Double.parseDouble(bla); 
    } catch (Exception e) { 
     e.getMessage(); 
    } 

    System.out.println(showWithdrawal); 

你可以做這樣的

+0

不錯。這有幫助。謝謝。 – Progzilla

1
​​3210

這條線將拋出一個錯誤。你不能以double形式返回一個String。相反,你可以將其替換爲:

throw new InputMismatchException("Please, you need to select appropriate amount."); 

而且外面搭上這樣說:

try { 
    withdrawCash(); 
} catch (InputMismatchException e) { 
    System.out.println("Error withdrawing cash: " + e); 
} 
+0

感謝您的解決方案。它有幫助。 – Progzilla

+0

@webxpat很高興能幫到你:) –

0

可我也建議,爲了錢你不不要用雙。看看BigDecimal也是一樣。使用貨幣價值的雙倍值,你會遇到很多問題。

+0

工作正常!謝謝。 – Progzilla

相關問題