im working on a java program using GUI, and i ran into a problem whenever i try to add the values from the text fields and one is missing it doesn't work and i get an error but if all of them are available i get the right answer, how can i add without having all the values?
JButton btnCheckOut = new JButton("CHECK OUT");
btnCheckOut.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
double apples, strawberries, watermelon, tomatoe, carrot, beef, lamb, payment;
apples = Double.parseDouble(textField.getText());
strawberries = Double.parseDouble(textField_1.getText());
watermelon = Double.parseDouble(textField_2.getText());
tomatoe = Double.parseDouble(textField_3.getText());
carrot = Double.parseDouble(textField_4.getText());
beef = Double.parseDouble(textField_5.getText());
lamb = Double.parseDouble(textField_6.getText());
payment = (apples*8)+(strawberries*10)+(watermelon*14)+
(tomatoe*5)+(carrot*6)+(beef*25)+(lamb*20);
DecimalFormat df = new DecimalFormat("###.##");
textField_7.setText(String.valueOf(df.format(payment)));
}
});
Create an IF
statement that sets the variables to zero
if its respective TextField is empty, before you do the math operation.
if(textfield.getText().isEmpty())
{
apples = 0;
}
When you make your textFields, initialize the text there to 0. Like
JTextField textField_1 = new JTextField("0");
Or, you could add
if(textField.getText() == ""){
textField.setText("0");
}
For each text field before trying to parse to double.
Create eg getDoubleValue, which you apply to all your items when read. Simple as:
apples = getDoubleValue( textField.getText() );
...
...
then
public double getDoubleValue( String txt ) {
double d = 0d;
try {
if( txt != null && !txt.isEmpty() ) {
d = Double.parseDouble( txt );
}
} catch(Exception ex) {}
return d;
}
(This will also take care for "dirty input", if the textfield does not contain a number it will set it to zero during parse).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.