在 switch 中使用数组作为 case 语句

2022-01-19 00:00:00 arrays switch-statement java

我正在尝试做这样的事情,即在 switch 语句中使用数组.在Java中可能吗?如果不是,请说明一个可能的解决方案.

boolean[] values = new boolean[4];值 [0] = 真;值[1] = 假;值[2] = 假;值[3] = 真;开关(值){案例[真,假,真,假]:休息;案例[假,假,真,假]:休息;默认:休息;}

解决方案

NO,你根本做不到.

SwitchStatement:switch ( 表达式 ) SwitchBlock

<块引用>

表达式的类型必须是 char、byte、short、int、Character、Byte、Short、Integer、String 或枚举类型(第 8.9 节),否则会发生编译时错误.

http://docs.oracle.com/javase/specs/jls/se7/html/jls-14.html#jls-14.11

I am trying to do something like this, i.e., use an array in a switch statement. Is it possible in Java? If it isn't, please explain a possible solution.

boolean[] values = new boolean[4];

values[0] = true;
values[1] = false;
values[2] = false;
values[3] = true;

switch (values) {
    case [true, false, true, false]:
        break;
    case [false, false, true, false]:
        break;
    default:
        break;
}

解决方案

NO, simply you cannot.

SwitchStatement:
    switch ( Expression ) SwitchBlock

The type of the Expression must be char, byte, short, int, Character, Byte, Short, Integer, String, or an enum type (§8.9), or a compile-time error occurs.

http://docs.oracle.com/javase/specs/jls/se7/html/jls-14.html#jls-14.11

相关文章