如何在java中将空文本框值传递给零值?

时间:2016-07-22 08:54:49

标签: java

我的java应用程序中有四个文本框。 所以我需要输入所有值作为双值。 我的senario是这样的 如果我没有在我的文本框中输入任何数字。

双值应为零。 如果输入任何值,它应该给我输入的值为double。

将所有字符串值转换为double值。 双变量已初始化为0.0

Double priceSec=0.0;
Double priceThird=0.0;
Double priceFourth=0.0;
Double priceFifth=0.0;

String priceTwo = cusPrice2.getText();
String priceThree = cusPrice3.getText();
String priceFour = cusPrice4.getText();
String priceFive = cusPrice5.getText();

priceSec = Double.parseDouble(priceTwo);
priceThird = Double.parseDouble(priceThree);
priceFourth = Double.parseDouble(priceFour);
priceFifth = Double.parseDouble(priceFive);

我将double值初始化为0.0,因为如果我没有在文本框中输入任何值。默认值为零。

但所有这些编码都给我一个错误:

  

线程中的异常“AWT-EventQueue-0”java.lang.NumberFormatException:empty String       at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:1842)       在sun.misc.FloatingDecimal.parseDouble(FloatingDecimal.java:110)

2 个答案:

答案 0 :(得分:1)

您可以这样做:您可以使用try-catch子句来控制Exception

首先创建一个将String转换为double

的方法
private double getValue(String textBoxData) {
    try {
        // parse the string value to double and return
        return Double.parseDouble(textBoxData);
    } catch (NumberFormatException e) {
        // return zero if exception accrued due to wrong string data
        return 0;
    }
}

现在你可以这样使用:

// now you can get the double values as below:
priceSec = getValue(priceTwo);
priceThird = getValue(priceThree);
priceFourth = getValue(priceFour);
priceFifth = getValue(priceFive);

// Now you can do the work with your prices data

答案 1 :(得分:1)

您可以为Double.parseDouble()创建一个包装器方法,并在需要时调用它。

priceSec = convertToDouble(priceTwo);

private static Double convertToDouble(String textValue) {
    double doubleValue;
    try {
        doubleValue = Double.parseDouble(textValue);    
    } catch (Exception e) {
        doubleValue = 0.0;
    }

    return doubleValue;
}