2015-04-02 40 views
3

我的代码如下所示:进行切换的情况下执行以往的案例

switch(read.nextInt()){ 
     case 1: 
      //do "a" and print the result 
      break; 
     case 2: 
      //do "b" and print the result 
      break; 
     case 3: 
      //do "a" and print the result 
      //do "b" and print the result 
    } 

是否有另一种方式做到这一点并不简单地复制里面有什么情况下1和2? 我刚开始我的毕业,所以我只能用字符串并为此扫描仪,谢谢:)

回答

0

一个棘手的,IMO更具可读性:

int nextInt = read.nextInt(); 
if (nextInt % 2 == 1) { // or if (nextInt == 1 || nextInt == 3) { 
    // do "a" and print the result 
} 
if (nextInt > 1) { 
    // do "b" and print the result 
} 
+0

也许我不允许创建方法,而且这个答案非常合适,谢谢 – 2015-04-02 21:53:12

2

定义两种方法称为doA()doB()并给他们打电话。这样你就不会复制你的代码。您是否确定在每个case声明后不需要break声明?

switch(read.nextInt()){ 
     case 1: 
      doA(); 
      break; 
     case 2: 
      doB(); 
      break; 
     case 3: 
      doA(); 
      doB(); 
      break; 
     default: 
      // do something 
      break; 
    } 
+0

我忘了写,但是在我的代码中有break语句,谢谢! – 2015-04-02 21:39:59

+0

更新了代码。有一个默认情况也是一个很好的做法。 – 2015-04-02 21:40:49

0

在这样的情况下,它可能是有道理为

//do "a" and print the result 

//do "b" and print the result 

创建方法如果3你只需调用这些方法一前一后。

0

您好像忘了 '休息'。它使switch语句中的代码“中断”。如果你在“1” &“2”做同样的事情,在“3”的其他东西的情况下的情况下想,你可以写:

switch(read.nextInt()){ 
     case 1: 
     case 2: 
      //do "a" or "b" and print the result 
      break; //break from switch statement, otherwise, the code below (yes, I mean "case 3") will be executed too 
     case 3: 
      //do "a" and print the result 
      //do "b" and print the result 
    } 

这是加入“破发”,在一个平常的事情如果你不想让相同的代码块被执行几个值,那么“case”块的结尾:

switch(n){ 
     case 1: 
      //do something 
      break; 
     case 2: 
      //do other things 
      break; 
     case 3: 
      //more things! 
      //you may not write "break" in the last "case" if you want 
    } 
相关问题