2017-10-31 11 views
0

私はSwingで否定的な問題を抱えています。何らかの理由でBig Decimalの否定と加算が機能しません。コードはコンパイルされますが、マイナスとプラスの計算は機能しません。BigDecimalの計算が機能しないのはなぜですか?

コードスニペット

//Convert the JLabel to a Double so we can perform negation. 
diallerPanelSum = new BigDecimal(balanceAmount.getText()); 

//Dont allow the Balance to go negative! 
if(diallerPanelSum.compareTo(BigDecimal.ZERO)>0) 
    { 

     if(e.getSource()==buttonMakeCall) 
     { 
      diallerPanelSum.subtract(new BigDecimal("1.0")); 
     } 

     if(e.getSource()==buttonSendText) 
     { 
      diallerPanelSum.subtract(new BigDecimal("0.10")); 
     } 

     if(e.getSource()==buttonTopUp) 
     { 
      diallerPanelSum.add(new BigDecimal("10.00")); 
     } 

    } 

//Convert the Float back to a JLabel 
balanceAmount.setText(String.valueOf(diallerPanelSum)); 

答えて

1

BigDecimals不変です。したがって、add()またはsubtract()のような演算の結果をnewBigDecimalを生成するので、BigDecimalに再度割り当てる必要があります。これを代わりに試してみてください:

if (diallerPanelSum.compareTo(BigDecimal.ZERO) > 0) 
{ 

    if (e.getSource() == buttonMakeCall) 
    { 
     diallerPanelSum = diallerPanelSum.subtract(BigDecimal.ONE); 
    } 

    if (e.getSource() == buttonSendText) 
    { 
     diallerPanelSum = diallerPanelSum.subtract(new BigDecimal("0.10")); 
    } 

    if (e.getSource() == buttonTopUp) 
    { 
     diallerPanelSum = diallerPanelSum.add(BigDecimal.TEN); 
    } 

} 
+0

diallerPanelSumはすでにBigDecimalです – Ninja2k

+0

試しましたか?既存の 'BigDecimal'は変更されていないので、' add() 'または' subtract() '(新しいオブジェクト)の結果を' diallerPanelSum'に再度割り当てる必要があります。ドキュメントをお読みください。 –

+0

ああ、私はコードを誤解しました!はい、うまくいきました! – Ninja2k

関連する問題