Passing a value from one case to another in switch statement

社会主义新天地 提交于 2020-01-07 04:13:04

问题


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.



来源:https://stackoverflow.com/questions/16621708/passing-a-value-from-one-case-to-another-in-switch-statement

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!