int time;try { time = Integer.parseInt(JOptionPane.showInputDialog("Enter seconds"));} catch (NumberFormatException e) { //error}Integer.parseInt``NumberFormatException如果无法解析,则会抛出一个
int。如果您只想在输入无效的情况下重试,则将其包装成这样的
while循环:
boolean valid = false;while (!valid) { int time; try { time = Integer.parseInt(JOptionPane.showInputDialog("Enter seconds")); if (time >= 0) valid = true; } catch (NumberFormatException e) { //error JOptionPane.showConfirmDialog("Error, not a number. Please try again."); }}


