2016-07-22 79 views
1

我在我的java應用程序中有四個文本框。 所以我需要輸入所有值爲雙值。 我的senario是這樣的 如果我沒有輸入任何數字到我的文本框。如何在java中將空文本框值傳遞給零值?

雙值應該爲零。 如果輸入任何值,它應該給我輸入的值爲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); 

我初始化雙重價值爲0.0,因爲如果我沒有輸入的任何值到文本框。默認值將爲零。

但所有這些編碼給了我這樣的錯誤:

在線程異常 「的AWT - EventQueue的 - 0」 java.lang.NumberFormatException:空字符串 在sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal的.java:1842) 在sun.misc.FloatingDecimal.parseDouble(FloatingDecimal.java:110)

+0

如果有可能是一個空字符串,那麼你必須檢查並適當處理它。 – ChiefTwoPencils

+0

空字符串不一定表示0,但也可以表示空或其他。因此你必須相應地處理它。還要注意,該字符串可能包含非數字文本(例如「hello there」),因此您也必須處理該文本。 – Thomas

回答

1

你能做到這樣的:你可以使用try-catch子句來控制Exception

首先創建一個方法來轉換Stringdouble

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 
+0

如果我有四個文本框,該怎麼辦?並假設我輸入第一個和第二個文本框的值,並將其他兩個文本框留爲空? –

+0

答案已更新,你可以查看。祝你好運! –

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; 
} 
相關問題