Search code examples
javarandombukkitillegalargumentexception

java.lang.IllegalArgumentException: bound must be positive(java.util.concurrent.ThreadLocalRandom.nextInt(Unknown Source) ~[?:1.8.0_301])


Get an error saying that my bound must be positive. The error comes from this line :
return mapNames[ThreadLocalRandom.current().nextInt(mapNames.length)];

The place where I set mapNames is here :
String[] mapNames = mapsConfiguration.getKeys(false).toArray(new String[]{});

The place where I set mapsConfigurationis here :
private ConfigurationSection mapsConfiguration;

And here is my method where it is :

public String randomMapName()
{
    String[] mapNames = mapsConfiguration.getKeys(false).toArray(new String[]{});
    return mapNames[ThreadLocalRandom.current().nextInt(mapNames.length)];
}

I get this stacktrace :

        java.lang.IllegalArgumentException: bound must be positive
        at java.util.concurrent.ThreadLocalRandom.nextInt(Unknown Source) ~[?:1.8.0_301]
        at com.proboxinjet.ashguardall.minigame.bedwars.config.ConfigurationManager.randomMapName(ConfigurationManager.java:47) ~[?:?]
        at com.proboxinjet.ashguardall.minigame.bedwars.gamemanager.GameManager.<init>(GameManager.java:37) ~[?:?]
        at com.proboxinjet.ashguardall.AshGuardAll.onEnable(AshGuardAll.java:23) ~[?:?]
        at org.bukkit.plugin.java.JavaPlugin.setEnabled(JavaPlugin.java:263) ~[spigot.jar:3096-Spigot-9fb885e-296df56]
        at org.bukkit.plugin.java.JavaPluginLoader.enablePlugin(JavaPluginLoader.java:342) ~[spigot.jar:3096-Spigot-9fb885e-296df56]
        at org.bukkit.plugin.SimplePluginManager.enablePlugin(SimplePluginManager.java:480) ~[spigot.jar:3096-Spigot-9fb885e-296df56]
        at org.bukkit.craftbukkit.v1_16_R3.CraftServer.enablePlugin(CraftServer.java:492) ~[spigot.jar:3096-Spigot-9fb885e-296df56]
        at org.bukkit.craftbukkit.v1_16_R3.CraftServer.enablePlugins(CraftServer.java:406) ~[spigot.jar:3096-Spigot-9fb885e-296df56]
        at net.minecraft.server.v1_16_R3.MinecraftServer.loadWorld(MinecraftServer.java:554) ~[spigot.jar:3096-Spigot-9fb885e-296df56]
        at net.minecraft.server.v1_16_R3.DedicatedServer.init(DedicatedServer.java:257) ~[spigot.jar:3096-Spigot-9fb885e-296df56]
        at net.minecraft.server.v1_16_R3.MinecraftServer.w(MinecraftServer.java:928) ~[spigot.jar:3096-Spigot-9fb885e-296df56]
        at net.minecraft.server.v1_16_R3.MinecraftServer.lambda$0(MinecraftServer.java:273) ~[spigot.jar:3096-Spigot-9fb885e-296df56]
        at java.lang.Thread.run(Unknown Source) [?:1.8.0_301]```

Solution

  • The docs of ThreadLocalRandom.nextInt(int bound) say:

    bound the upper bound (exclusive). Must be positive.

    The first line of the method is:

    if (bound <= 0)
        throw new IllegalArgumentException(BAD_BOUND);
    

    Though I'd say that your mapNames array is empty and you pass 0 to nextInt which then results in IllegalArgumentException