使一个switch case执行之前的case

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个案例中的内容? 我刚开始毕业,所以只能使用 StringScanner,谢谢 :)

4个回答

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;
    }

我忘记写了,但是我的代码中有break语句,谢谢! - João Oliveira
更新了代码。同时,添加一个默认情况也是一个好的实践。 - user3248346

0

一个棘手的问题,我认为更易读:

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
}

也许我还没有权限创建方法,这个答案非常适合,谢谢。 - João Oliveira

0
在这种情况下,创建方法可能是有意义的。
//do "a" and print the result

并且

//do "b" and print the result

在第三种情况下,您只需依次调用这些方法。

0

看起来你忘记了 'break'。它可以让代码从 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”块的结尾添加“break”通常是一件很普遍的事情:

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
    }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接