Java switch语句中的多个/重复个案

Cod*_*key 4 java multiple-instances switch-statement

我想知道Java如何处理同一个案例的多个相同实例.从概念上讲,我认为以下内容是有道理的:

switch (someIntegerValue)
{
   case 1:
   case 2:
      DoSomethingForBothCases();
      break;
   case 3:
      DoSomethingUnrelated();
      break;
   case 1:
      DoSomethingForCase1ThatReliesUponExecutionOfTheEarlierFunctionCall();
      break;
   case 2:
      DoSomethingForCase2ThatReliesUponExecutionOfTheEarlierFunctionCall();
      break;
}
Run Code Online (Sandbox Code Playgroud)

本质上,我想为一个案例1或2(使用直通)执行一大块代码,但是稍后,只有一个代码块仅针对案例2执行.

相反,以下是必要的吗?

switch (someIntegerValue)
{
   case 1:
      DoSomethingForBothCases();
      DoSomethingForCase1ThatReliesUponExecutionOfTheEarlierFunctionCall();
      break;
   case 2:
      DoSomethingForBothCases();
      DoSomethingForCase2ThatReliesUponExecutionOfTheEarlierFunctionCall();
      break;
   case 3:
      DoSomethingUnrelated();
      break;
}
Run Code Online (Sandbox Code Playgroud)

我的实际代码更复杂,但会使用相同的原则(例如" 案例1:nope;好吧...... 案例2:是的!执行此代码!; 案例3:nope; 案例1再次?:仍然没有! ; 案例2再次?:是的!执行此代码; 没有更多案例:全部完成!")

Boh*_*ian 5

两个switch语句有什么问题吗?

switch (someIntegerValue) {
   case 1:
   case 2:
      DoSomethingForBothCases();
      break;
   case 3:
      DoSomethingUnrelated();
      break;
}

switch (someIntegerValue) {
   case 1:
      DoSomethingForCase1ThatReliesUponExecutionOfTheEarlierFunctionCall();
      break;
   case 2:
      DoSomethingForCase2ThatReliesUponExecutionOfTheEarlierFunctionCall();
      break;
}
Run Code Online (Sandbox Code Playgroud)

这就是我要做的.


Geo*_*off 1

不能在 Java switch 语句中重复 case,这是一个编译错误。您需要按照您的建议进行操作,这实际上看起来是一个很好的因式分解。