Search code examples
javaprobability

Java Probability (Percentage Based) 3 Choices


I am just looking to confirm that this code would be correct for what I am looking for. Basically, I would like when called, this function to roll a number out of a certain rarity. The rarities right now are 15% chance, 20% chance, and a 65% common chance. However, after rereading my code, it seems to be that the 20% chance actually is a lower chance than the 15% chance which would not be ideal. Could someone check this for me? Thanks!

    public void roll() {
        float rarity = random.nextFloat();

        if(rarity <= 0.15f) {
            // Roll Legendary Item
        } else if(rarity <= 0.35) {
            // Roll Rare Item
        } else {
            // Roll Common Item
        }
    }

Solution

  • It should be

    else if(rarity <= 0.35f) 
    

    The way your code is written, it is currently 15%-5%-80%