I have a JTextField that I’m not always passing a value to, but it causes a NumberFormatException error to be thrown when the program runs if the person hasn’t entered anything into the JTextField. I have some code below that I’m trying to convert a null response into a different String value. Why isn’t it assigning stringInput as a String of “0”?
public int getOptionalDinners()
{
try
{
// get the input from the text field and determine if it's more than 0
String stringInput = " ";
stringInput = dinnerTextField.getText();
if (stringInput == null)
stringInput = "0";
int validAmount = Integer.parseInt(stringInput);
if (validAmount < 0)
throw new IllegalArgumentException();
dinnerQuantity = validAmount * 30;
}
catch (NumberFormatException error)
{
JOptionPane.showMessageDialog (null, "The number of dinners needs to be numeric.",
"Input Error", JOptionPane.ERROR_MESSAGE);
}
catch (IllegalArgumentException error)
{
JOptionPane.showMessageDialog (null, "The number of dinners needs to be higher than 0.",
"Input Error", JOptionPane.ERROR_MESSAGE);
}
return dinnerQuantity;
}
try
You also need to check if it is 0 length.
Then assign the value back to the JTextField.