我有一个JTextField,但我并不总是将值传递给它,但是如果该人没有在JTextField中输入任何内容,则它将导致在程序运行时引发NumberFormatException错误。我下面有一些代码,我试图将空响应转换为另一个String值。为什么不将stringInput分配为字符串“ 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;
}

最佳答案

尝试

if (stringInput == null || stringInput.length() == 0)  {
  stringInput = "0";
}


您还需要检查它的长度是否为0。

然后将值分配回JTextField。

dinnerTextField.setText(stringInput);

09-30 12:13