java数字格式异常,如何解决数字格式异常:空字符串

In my project I'm putting a JTextField to set grand total in the invoice. Its name is txtGtotal. When the customer pays an advance he type its value in txtAdvance JTextField, and I wrote a cord to txtAdvance's keyreleasing to set the due payment to txtDue JTextField. (If customer didn't pay any advance he should type as 0 in txtAdvance and txtDue also set 0)

Given below is my cord to key event.

private void txtAdvanceKeyReleased(java.awt.event.KeyEvent evt) {

double gtotal = Double.parseDouble(txtGtotal.getText());

double ad = Double.parseDouble(txtAdvance.getText());

double due = gtotal - ad;

}

My question is when I'm clearing the number value in txtAdvance and try to type another number value before typing I'm getting this java.lang.NumberFormatException: empty String error. But after I replaced that empty txtAdvance jtextfeild with a number value, system is wording properly. How can I stop that error. As they showing error is in second line of the cord. which make a variable called double ad.

解决方案

How about the obvious solution:

private void txtAdvanceKeyReleased(java.awt.event.KeyEvent evt) {

double gtotal = parseDouble(txtGtotal.getText());

double ad = parseDouble(txtAdvance.getText());

double due = gtotal - ad;

}

private double parseDouble(String s){

if(s == null || s.isEmpty())

return 0.0;

else

return Double.parseDouble(s);

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值