我看了其他问题,还是想不通。为什么它不让我用 switch 语句编译这段代码?我收到典型错误“case expressions must be constant expressions”的错误。我正在尝试从消息中打开字节。由于速度问题,我想使用开关并尽量不进行任何转换,即从 int 到 byte。我的 Utils 类包含一个带有 A、B、C...的枚举 PID。我想打开这些,但我收到的消息以字节为单位。
public class SomeClass extends Thread {
public static final byte myCase1 = (byte) Utils.PID.A.ordinal();
public static final byte myCase2 = (byte) Utils.PID.B.ordinal();
public static final byte myCase3 = (byte) Utils.PID.C.ordinal();
private double[] findAllData(ByteBuffer message) {
byte[] byteBuffer = new byte[9000];
// parse through and find all PIDs
for(int i=0 ;i < message.capacity(); i++) {
message.position(i);
switch (message.get(i)) {
case myCase1 : break; // Compiler errors at the case statements
case myCase2 : break;// Compiler errors at the case statements
case myCase3 : break;// Compiler errors at the case statements
}
}
}
// Utility class
public class Utils {
public enum PID { A,B,C };
}
最佳答案
尽管 myCase1
是一个常量,但它在编译时不是已知的常量。
相反,我会打开枚举
private static final Utils.PID[] PIDS = Utils.PID.values();
private double[] findAllData(ByteBuffer message) {
byte[] byteBuffer = new byte[9000];
// parse through and find all PIDs
for (int i = 0; i < message.capacity(); i++) {
message.position(i);
switch (PIDS[message.get(i)]) {
case A:
break;
case B:
break;
case C:
break;
}
}
例如这是行不通的
private static final int NUM1 = Integer.getInteger("num1"); // from command line properties
private static final int NUM2 = Integer.getInteger("num2"); // from command line properties
switch(num) {
case NUM1: break;
case NUM2: break;
}
关于java - 开关编译错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8125460/