1

我在检查枚举值的索引时遇到问题,我有一个带有可变参数整数的枚举,如果该整数大于 1 并且是可替换项,那么当我获得下一个索引时,我将其加一。但是,当增量之后没有另一个整数时,游戏崩溃了,我在过去半小时左右一直在尝试解决这个问题,我似乎无法检查它是否是其中的最后一个索引枚举。我知道这是一个非常本地化的问题,但我需要一些帮助。

编码:

private int getNextId(Food food, int id) {
    if (food.getType().equals(REPLACE)) {
        for (int i = 0; i < food.getIds().length; i++) {
            if (food.getIds()[i] == id) {
                return food.getIds()[i + 1];
            }
        }
    }
    return -1;
}

枚举:

private enum Food {
    SHRIMP(REMOVE, 3, 315),
    LOBSTER(REMOVE, 12, 379),
    MANTA_RAY(REMOVE, 22, 391),
    MONKFISH(REMOVE, 16, 7946),
    MACKREL(REMOVE, 6, 355),
    SALMON(REMOVE, 9, 329),
    SEA_TURTLE(REMOVE, 22, 397),
    SHARK(REMOVE, 20, 385),
    SWORDFISH(REMOVE, 14, 373),
    TROUT(REMOVE, 7, 333), 
    TUNA(REMOVE, 10, 361),
    TUNA_POTATO(REMOVE, 22, 7060),

    CAKE(REPLACE, 4, 1891, 1893, 1895),
    CHOCOLATE_CAKE(REPLACE, 5, 1897, 1899, 1901),
    PLAIN_PIZZA(REPLACE, 7, 2289, 2291),
    MEAT_PIZZA(REPLACE, 8, 2293, 2295),
    ANCHOVY_PIZZA(REPLACE, 9, 2297, 2299),
    PINEAPPLE_PIZZA(REPLACE, 11, 2301, 2303),
    APPLE_PIE(REPLACE, 7, 2323, 2335),
    REDBERRY_PIE(REPLACE, 5, 2325, 2333),
    MEAT_PIE(REPLACE, 6, 2327, 2331);

    private final ConsumableType type;

    private final int healAmount;

    private final int[] ids;

    private Food(ConsumableType type, int healAmount, int... ids) {
        this.type = type;
        this.ids = ids;
        this.healAmount = healAmount;
    }

    public ConsumableType getType() {
        return type;
    }

    public int getHealAmount() {
        return healAmount;
    }

    public int[] getIds() {
        return ids;
    }

    public String getName() {
        return name().toLowerCase().replaceAll("_", " ");
    }

}

哦,另一个注意事项,我尝试检查它是-1还是0,但就像我说的那样,我似乎无法弄清楚。提前致谢。

4

1 回答 1

1

你想做这样的事情吗?

private int getNextId(Food food, int id) {
    if (food.getType().equals(REPLACE)) {
        int n = food.getIds().length;
        for (int i = 0; i < n; i++) {
            if (food.getIds()[i] == id && (i+1) < n) {
                return food.getIds()[i + 1];
            }
        }
    }
    return -1;
}

上述方法中,只有存在时才会返回下一个Id,否则返回-1。

于 2013-04-01T16:29:40.570 回答