我试图将String解析为Double,这可能吗?

时间:2014-05-05 14:48:56

标签: java parsing methods

请问这是聪明还是愚蠢..我试图在double类型的方法中返回一个String ..

 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;
    } 
}

请告诉我理想的解决方案

3 个答案:

答案 0 :(得分:1)

double showWithdrawal = Double.parseDouble(complainWithdrawal);

此行将引发错误。您不能将String作为double返回。相反,您可以将其替换为:

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

然后像这样抓住它:

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

答案 1 :(得分:0)

    String bla = "12.25";

    double showWithdrawal = 0;

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

    System.out.println(showWithdrawal);

你可以这样做

答案 2 :(得分:0)

我还可以建议,为了钱,你不要使用双倍。看看BigDecimal。如果使用双倍的货币价值,你将遇到很多问题。

相关问题