vendredi 11 août 2017

IllegalArgumentException: Bound must be positive when using Random() method in Java

//in a method that checks players equipment to change damage and armor values
    //none of these min/max values should spit out anything less than 0
        switch(weapon)
        {
            case"Knife": minDamage = 3; maxDamage = 12; break;
            case"Short Sword": minDamage = 6; maxDamage = 15; break;
            case"Long Sword": minDamage = 8; maxDamage = 20; break;
            case"Battle Axe": minDamage = 14; maxDamage = 28; break;
            case"Death's Blade": minDamage = 20;maxDamage = 60; break;
        }
        //armor

        switch(armor)
        {
            case"Rags": playerArmor = 0; break;
            case"Hide Armor": playerArmor = 5; break;
            case"Leather Armor": playerArmor = 8; break;
            case"Chainmail": playerArmor = 12; break;
            case"Platemail": playerArmor = 20; break;
            case"Death's Armor": playerArmor = 50; break;
        }


        //in a method that handles the combat
        //The problem is somewhere in the logic for the damageDealt integer.
        int damageDealt = rand.nextInt(maxDamage - minDamage + 1)+minDamage;
        int damageTaken = rand.nextInt(enemyDamage - playerArmor);
        if(damageDealt >= 0)
        {
                enemyHealth -=damageDealt;
        }
        else
        {
                damageDealt = 0;
        }
        if(damageTaken>0)
        {
                playerHealth -=damageTaken;
        }
        else
        {
                damageTaken = 0;    
        }

So this is just a few lines of code from a Text adventure I'm finishing up. Sometimes I will get this bug that pops up saying IllegalArgumentException: Bound must be positive for java's random() method during the combat. The first blurb of code is part of a method that handles the players inventory. Take note that every max value for the weapons is larger than the respective min value as they should be. The second blurb of code is part of the combat method. When the player chooses to attack, those lines are run. The damageDealt integer seems to be the issue as far as I can tell. I'm fairly certain that "int damageDealt = rand.nextInt(maxDamage - minDamage + 1)+minDamage;" should work and never give an integer value below the minDamage value or even zero for that matter. But, for some reason sometimes it does and the game freaks out and gives that error code. The issue doesn't occur if I only use maxDamage, but this isn't optimal because then a super high power weapon can do just as little damage as the starting weapon. If you guys can figure out a solution that would fix my code or even a whole different way to handle randomly choosing a number in an integer range, I would greatly appreciate it :) Thanks!




Aucun commentaire:

Enregistrer un commentaire