java中switch的case2怎样调用case 1中的数据

2025-03-17 06:28:51
推荐回答(5个)
回答1:

定义一个Array集合,泛型是什么取决于自己的需求,case2中break前把要调用的东西用list.add()装到集合里面,case1循环集合,输出即可

回答2:

这里是switch执行分析:http://zhidao.baidu.com/question/1690127680831152228.html

switch不是循环,代码走到case 1遇到break;后自然会中断switch并执行switch之后的代码。如果你非要这样做,可以利用java引用对象来做。

静态变量(全局引用,一次实例化)

public class $ {
    public static Test t = new Test();
    public static void main(String[] args) {
        test(1);
        test(2);
        
    }
    public static void test(int i) {
        switch (i) {
        case 1:
            if(t == null) t = new Test();
            t.str = "你好";
            break;
        case 2:
            System.out.println(t.str);
            break;
        default:
            break;
        }
    }
}
class Test {
    int a = 12;
    String str = "Hello";
}

或者将对象带入方法(带入方法的对象必须保证不为null,否则空指针异常)

public class $ {
    public static void main(String[] args) {
        Test t = new Test();
        test(t, 1);
        test(t, 2);
        
    }
    public static void test(Test t, int i) {
        switch (i) {
        case 1:
            if(t == null) t = new Test();
            t.str = "你好";
            break;
        case 2:
            System.out.println(t.str);
            break;
        default:
            break;
        }
    }
}
class Test {
    int a = 12;
    String str = "Hello";
}

回答3:

这个直接调用是不受到语法支持的,你要么就是把case 1里面的操作写成一个方法,然后case 2里面也调用者方法,获取必要的值

回答4:

1,可以提供一个静态变量,将case 1里的变量保存到静态变量中
2,写一个公共方法,1和2里都调用这个方法
实现的方法还是挺多的

回答5:

wolegecao,加了case2执行连case1都直接跳过了,哪里还来得case1里面的数据,你这是逗谁呢~