我在使用 Swing 时遇到求反问题,由于某种原因,我的大十进制求反和加法不起作用,我的代码可以编译,但减号和加号计算不起作用,非常感谢任何帮助。
代码片段
//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));
最佳答案
BigDecimals
是不可变的。因此,您必须再次将 add()
或 subtract()
等操作的结果分配给 BigDecimal
,因为它们会生成 新 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);
}
}
关于java - 为什么我的 BigDecimal 计算不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47042052/