有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java开关编译错误

我已经看了其他问题,但仍然无法理解。为什么不让我用switch语句编译这段代码呢?我得到一个错误,典型的错误是“case表达式必须是常量表达式”。我正试图打开消息中的字节。由于速度问题,我想使用该开关,尽量不进行任何转换,即从int到byte的转换。我的Utils类包含一个带有A、B、C。。。在里面。我想打开这些,但我收到的信息是以字节为单位的

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 };
}

共 (1) 个答案

  1. # 1 楼答案

    尽管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;
    }