case 6:
case 7:
case 8:
JOptionPane.showMessageDialog(null,"That is totally unbelieveable.");
break;
这将完成这项工作。
但是我会将其更改为:
case 4: JOptionPane.showMessageDialog(null,"Four dogs is too many."); break;
case 5: JOptionPane.showMessageDialog(null,"Five dogs means you're a crazy person."); break;
default: JOptionPane.showMessageDialog(null,"That is totally unbelieveable.");break;
这将消除 Invalid Output 消息,但适用于每个大于 5 的数字,但我认为这是可以接受的,因为 dogs 的价值来自于一个Integer.parseInt()
电话。如果内容无效,则会在那里抛出异常,并且可以在异常处理程序中显示无效输入消息,同样,如果 dog 是否定的,则可以抛出异常。
这具有适用于各种狗的优势。case
如果需要管理不同的错误消息,只需添加特定的分支就足够了。
int dogs;
try {
dogs = Integer.parseInt(JOptionPane.showInputDialog("How many dogs do you have?"));
if (dogs < 0) {
throw new Exception("Negative dog is impossible!");
}
switch (dogs)
{
...
...
...
case 4: JOptionPane.showMessageDialog(null,"Four dogs is too many."); break;
case 5: JOptionPane.showMessageDialog(null,"Five dogs means you're a crazy person."); break;
default: JOptionPane.showMessageDialog(null,"That is totally unbelieveable.");break;
}
} catch (Exception e) {
JOptionPane.showMessageDialog(null,"Invalid input.");
}