如何解决数字格式异常

如何解决数字格式异常

本文介绍了如何解决数字格式异常:空字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的项目中,我要放置一个JTextField以在发票中设置总计.名称为txtGtotal.当客户支付预付款时,他在txtAdvance JTextField中键入其值,然后我在txtAdvance的密钥释放中写了一条代码,以将应付款项设置为txtDue JTextField. (如果客户不支付任何预付款,则应在txtAdvance中输入0,并且txtDue也应设置为0)

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;
}

我的问题是,当我清除txtAdvance中的数字值并尝试在键入之前键入另一个数字值时,得到此java.lang.NumberFormatException:空字符串错误.但是在我用数字值替换了空的txtAdvance jtextfeild之后,系统的措词正确.如何停止该错误.由于它们显示错误,所以在电线的第二行.会产生一个称为double 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.

推荐答案

明显的解决方案如何:

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);
}

这篇关于如何解决数字格式异常:空字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-31 20:13