TheCoder24
TheCoder24

Reputation: 47

Java Enum Returns Null

I am currently creating a plugin for Minecraft using the SpigotAPI. Reason I'm posting this here is because this I believe is a Java error. I am creating a duels plugin where inside my code it'll loop through an enum, and see if it's a specific type. The first time using it around it properly works, no problems. But when I try it for a second time without restarting my plugin/program/code it'll return the enum as null. Here is the code, is there a fix to this?

public DuelArenas[] getArenasWithType(DuelTypes type) {
    String suffix = "_NORMAL";
    List<DuelArenas> arenasAsList = new ArrayList<>();
    switch (type) {
        case NORMAL:
            suffix = "_NORMAL";
            break;
    }
    for (DuelArenas arena : duelArenaStatus.keySet()) {
        if (arena.toString().endsWith(suffix)) {
            arenasAsList.add(arena);
        }
    }
    DuelArenas[] arenas = new DuelArenas[arenasAsList.size()];
    return arenasAsList.toArray(arenas);
}

Stacktrace:

Caused by: java.lang.NullPointerException
    at me.nick.acore.duels.DuelsAPI.getArenasWithType(DuelsAPI.java:97) ~[?:?]

And yes I've checked to see if the enum was null, and it was in fact null. Also line 97 is

if (arena.toString().endsWith(suffix)) {

And finally here is the DuelArena class

public enum DuelArenas {

ARENA_1_NORMAL, ARENA_2_NORMAL, ARENA_3_NORMAL, ARENA_4_NORMAL, ARENA_5_NORMAL,
ARENA_6_NORMAL, ARENA_7_NORMAL, ARENA_8_NORMAL, ARENA_9_NORMAL, ARENA_10_NORMAL,
ARENA_11_NORMAL, ARENA_12_NORMAL }

Thanks!

Upvotes: 0

Views: 2134

Answers (1)

Will Fisher
Will Fisher

Reputation: 413

Your problem is that you cannot directly convert your custom DuelArenas class to a string. However when you are comparing to see if a .toString() ends with suffix, I feel that something is also going wrong. You would only ever use .toString to convert things like numbers to strings, and if your are converting a number to a string there is no way it will end in _NORMAL.

So if you want me to troubleshoot further please post your DuelArenas class, but until then my best guess is that when you do arena.toString you are looking to pull some sort of value from that class that is stored in it, and to do this you would do arena.variableInsideArenaName and work with that.

EDIT:
After seeing the class scratch that, the error in going to be somewhere in this line DuelArenas arena : duelArenaStatus.keySet()

Upvotes: 1

Related Questions