1

如果用户输入 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
4

4 回答 4

4

检查一个无效的数字,然后只使用一个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;
  }
}
于 2013-09-20T15:23:33.193 回答
3
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.");
} 
于 2013-09-20T15:23:24.507 回答
3

只需添加 7、8、9 和 6 的案例

case 6: 
case 7:
case 8:
case 9:
JOptionPane.showMessageDialog(null,"That is totally unbelieveable."); 
break;
于 2013-09-20T15:23:45.493 回答
0
import java.io.*;
import java.lang.*;
import java.util.*;

public class DogCheck {
 public static void main(String[] args) {
  int dogs;
  Scanner input = new Scanner(System.in);
  System.out.println("Enter Number of Dogs :");
  dogs=input.nextInt();
  if (dogs < 0)
      System.out.println("WoW! Aliens has arrived...")
  else 
  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;
  }
 }
}
于 2013-09-20T15:40:48.117 回答