我需要编写什么代码,以便用户输入7、8或9条狗;在情况6下仍会输出该消息?
int dogs;
dogs = Integer.parseInt(JOptionPane.showInputDialog("How many dogs do you have?"));
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;
case 6: JOptionPane.showMessageDialog(null,"That is totally unbelieveable.");
default: JOptionPane.showMessageDialog(null,"Invalid input.");
} // end switch
最佳答案
检查一个无效的数字,然后只使用default
子句:
if (dogs < 0) {
JOptionPane.showMessageDialog(null,"Invalid input.");
} else {
switch(dogs) {
// ...
case 5:
JOptionPane.showMessageDialog(null,"Five dogs means you're a crazy person.");
break;
default:
JOptionPane.showMessageDialog(null,"That is totally unbelieveable.");
break;
}
}