如何在switch case语句中匹配多个输入值?

时间:2013-09-20 15:21:14

标签: java switch-statement

如果用户输入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 个答案:

答案 0 :(得分: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;
  }
}

答案 1 :(得分: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;

这将消除无效输出消息,但将适用于每个数字&gt; 5,但我认为这是可以接受的,因为狗的价值来自Integer.parseInt()电话。如果内容无效,则会在那里抛出exceptin,并且可以在异常处理程序中显示Invalid Input消息,并且如果狗是负数,则可以抛出异常。

这具有适用于每一只狗的优点。如果需要管理不同的错误消息,只需添加特定的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.");
} 

答案 2 :(得分:3)

只需添加7,8,9和6

的案例
case 6: 
case 7:
case 8:
case 9:
JOptionPane.showMessageDialog(null,"That is totally unbelieveable."); 
break;

答案 3 :(得分: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;
  }
 }
}