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