How to fix Number Format Exception: empty String

天涯浪子 提交于 2021-01-28 14:23:39

问题


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.


回答1:


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



回答2:


to get rid of the empty String error you can do a simple check.

   private void txtAdvanceKeyReleased(java.awt.event.KeyEvent evt) {
      if(!txtGtotal.getText().trim().equals("") && !txtAdvance.getText().trim().equals("")){
        double gtotal = Double.parseDouble(txtGtotal.getText());
        double ad = Double.parseDouble(txtAdvance.getText());
        double due = gtotal - ad;
      }
    }



回答3:


You can say, that the action should not be fired on pressing Backspace, try this:

if(evt.getKeyCode() != 8){ //Backspace
    double gtotal = Double.parseDouble(txtGtotal.getText());
    double ad = Double.parseDouble(txtAdvance.getText());
    double due = gtotal - ad;
}


来源:https://stackoverflow.com/questions/19707977/how-to-fix-number-format-exception-empty-string

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!