2016-07-22 4 views
1

私は自分のJavaアプリケーションに4つのテキストボックスを持っています。 だから私はすべての値を二重の値として入力する必要があります。 私のsenarioはこのようです 私は私のテキストボックスに任意の番号を入力しなかった場合。どのように私は空のテキストボックスの値をjavaのゼロの2倍の値に渡すのですか?

二重値はゼロにする必要があります。 任意の値を入力すると、値iに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); 

として初期化 ダブル変数iは0.0とdouble型の値を初期化します。デフォルト値は0になります。

しかし、これらすべてのコーディングは私にこのようなエラーを与える:

例外スレッドで "AWT-EventQueueの-0" java.lang.NumberFormatException:空の文字列 sun.misc.FloatingDecimal.readJavaFormatStringで(FloatingDecimal .javaファイル:sun.misc.FloatingDecimal.parseDouble(FloatingDecimal.java:110)にて1842)

+0

一部の文字列が空文字列である可能性がある場合は、それをチェックして適切に処理する必要があります。 – ChiefTwoPencils

+0

空の文字列は、必ずしも0を意味するわけではありませんが、nullなどを意味する可能性もあります。したがって、それに応じてそれを処理する必要があります。また、文字列に数字以外のテキスト(「こんにちは」など)が含まれている可能性があるので、それも処理する必要があります。 – Thomas

答えて

1

あなたはこのようにそれを行うことができます:あなたはException

を制御するために try-catch句を使用することができます3210

まず今、あなたはこのように使用することができます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; 
    } 
} 

を変換するメソッドを作成:あなたはDouble.parseDouble(のラッパーメソッドを作成することができます

// 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

4つのテキストボックスがある場合はどうなりますか?最初のテキストボックスと2番目のテキストボックスの値を入力し、他の2つのテキストボックスを空のままにします。 –

+0

答えが更新されました。確認できます。がんばろう! –

1

)とするたびにそれを呼び出しますあなたが必要です。

priceSec = convertToDouble(priceTwo); 

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

    return doubleValue; 
} 
関連する問題