Passing a value from one case to another in switch

2019-08-29 17:35发布

问题:

So here is a sample code :

import java.util.Scanner;

public class Test {

public static void main(String[] args) {
    System.out.println("Please type in a number");
    Scanner in = new Scanner(System.in);
    switch (in.nextInt()){
        case 1:
            save(in);
            break;
        case 2:
            System.out.println(value);
            break;
        default:
            System.out.println("Default case");
            break;
    }               
    in.close();
}

public static String save(Scanner in){
System.out.println("Type in a word");
String value = in.next();
return value;
}
}

In this particular situation all I am trying to do here is to have access to the value that was stored in case 1.

回答1:

switch statement in all c-like languages including java is very general. It jumps to label according to the value of switch variable and then continues until break statement appears.

I am not sure what did you meant in your long explanation but in following example:

switch(op) {
    case ONE:
        foo();
    case TWO:
        bar();
        break;
    case THREE:
        aaa();
        qqq();
        break;
}

op == ONE first method foo() will be called, then the flow will arrive to block of TWO because no break statement was written in ONE, so bar() will be called. However then the break statement will jump the flow to code that appears just after the switch.

This is a short explanation. For more details find a good book or tutorial and read chapter about switch statement.