我有一個我並不總是傳遞值的JTextField,但是如果這個人沒有輸入任何東西到JTextField中,它會導致程序運行時拋出一個NumberFormatException錯誤。我下面有一些代碼,我試圖將空響應轉換爲不同的字符串值。爲什麼不將stringInput分配爲「0」字符串?如何將一個返回null的JTextField轉換爲不同的字符串值?
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;
}
而堆棧跟蹤?拋出哪個異常,以及哪裏? – claesv 2012-03-05 08:33:40
java.lang.Exception的 OptionalDinners.getOptionalDinners(OptionalDinners.java:70) RegistrationGUI $ CalcButtonListener.actionPerformed(RegistrationGUI.java:90) javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2018) javax.swing中。 AbstractButton的$ Handler.actionPerformed(AbstractButton.java:2341) javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402) javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259) – Jerinos 2012-03-05 08:37:52
和線路70是哪一行? – claesv 2012-03-05 08:41:52