简体   繁体   中英

Checking enum value index

I having an issue while checking the index of an enums value, I have an enum with a varargs integer, if that integer is greater than one and is a replaceable item, then when I get the next index I increment it by one. But, when there is not another integer after the increment, the game crashes, I've been trying to come up with a solution to this for the past half hour or so, I can't seem to check if its the last index within the enum. I know this is a very localized question but I need some help.

The code:

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

Enumeration:

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("_", " ");
    }

}

Oh and another note, I have tried for checking if it's -1 or 0 , but like I said I can't seem to figure it out. Thanks in advanced.

Are you trying to do something like this?

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

In the above method, the next Id will be returned only if it exists, otherwise -1 will be returned.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM