代码优化:对特定字符串求和整数值,

Code optimization: Sum integer values for specific string,

我正在编写 jave-me(Java ME 3.2) MIDlet,我在其中使用模式、风扇和温度变量(这个很简单)。当我将信息发送到网络 API 时,我必须将它们更改为十六进制值,因为 API 将它们读取为位。 对网络 API 的回复在此 format:AABBCC AA:mode - 8 位(自动、低、冷、风、热、N/A、N/A、OnOff) BB:fanSpeed - 8 位(自动、低、中、高,N/A、N/A、N/A、N/A) CC:temperature - 整数

因此,为了生成此响应,目前我使用此代码。但它可能会更短或更简单。那么我该如何优化这段代码:

int firstPart = 0;
    int seccondPart = 0;
    if(climateOn)
    {
        firstPart += 128;
    }
    if(mode.equals("HEAT"))
    {
        firstPart += 16;
    }
    if(mode.equals("WIND"))
    {
        firstPart += 8;
    }
    if(mode.equals("COOL"))
    {
        firstPart += 4;
    }
    if(mode.equals("LOW"))
    {
        firstPart += 2;
    }
    if(mode.equals("AUTO"))
    {
        firstPart += 1;
    }
    if(fanSpeed.equals("HIGH"))
    {
        seccondPart += 8;
    }
    if(fanSpeed.equals("MED"))
    {
        seccondPart += 4;
    }
    if(fanSpeed.equals("LOW"))
    {
        seccondPart += 2;
    }
    if(fanSpeed.equals("AUTO"))
    {
        seccondPart += 1;
    }
    return Integer.toHexString(firstPart) + ""  + Integer.toHexString(seccondPart) + "" +(setTemperature + 19);

你读过java enums吗?这是一个例子:

public enum Mode {
  Auto,Low,Cool,Wind,Heat,NA,OnOff;
}

枚举可以用在 switch 语句中。

您也可以为这些值中的每一个分配一个字节值。

如果您使用的是 Java 7 或更高版本,您可以使用 switch 语句:

switch (mode) {
    case "HEAT": firstPart += 16; break;
    case "WIND": firstPart += 8; break;
    // ...
}

另一种解决方案是将此数据放入地图中:

static final Map<String, Integer> modes = new HashMap<>();
static {
    modes.put("HEAT", 16);
    modes.put("WIND", 8);
    // ...
}

void someMethod(String mode) {
    // ...
    if (modes.containsKey(mode))
        firstPart += modes.get(mode);
}

您也可以像这样使用枚举:

enum Mode {
    HEAT(16), WIND(8), COOL(4), LOW(2), AUTO(1);
    private final int value;
    private Mode(int value) { this.value = value; }
    public int getValue() {return value;}
}

void someMethod() {
    // ...
    Mode mode = Mode.valueOf(str); // finds the named element. throws IllegalArgumentException
    firstPart += mode.getValue();
}

[编辑] 你甚至可以用枚举做得更好:

enum Mode {
    AUTO, LOW, COOL, WIND, HEAT;

    public int getValue() { return 1 << ordinal(); }
}

ordinal() 方法 return 枚举中特定常量的序号,从 0 开始。这意味着,它将 return 0 for AUTO, 1 表示 LOW, 等等。1 << N 是计算 2 的 N 次方的快速方法。

这样做的好处是,它会自动生成正确的值(假设顺序正确)并且不会为两个枚举生成相同的值。

用法与之前的枚举实现相同。