簡體   English   中英

制作一個開關案例執行以前的案例

[英]Make a switch case execute previous cases

我的代碼看起來像:

    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 ,謝謝:)

定義兩個方法稱為doA()doB()和調用它們。 這樣您就不會復制代碼了 您是否確定在每個case陳述后都不需要break語句?

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

在這種情況下,創建方法可能是有意義的

//do "a" and print the result

//do "b" and print the result

在案例3中,您將一個接一個地調用這些方法。

一個棘手的問題,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
}

看起來你已經忘記了'休息'。 它使代碼從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
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM