Home > database >  Random number between 1 - 6 [duplicate]
Random number between 1 - 6 [duplicate]

Time:09-27

I cannot figure out why my program is still outputting 0 when I run it, even though I have set the parameters between 1 - 6. I've tried using max - min min, and still outputs 0.

import java.util.Random;

//This is a random die simulator that outputs a random number between 1 and 6.

public class Main {

    public static void main(String[] args) {

        Random randGen = new Random();

        int die = randGen.nextInt(7)   1;
        
        System.out.println(randGen.nextInt(die));

    }
}

CodePudding user response:

Moral of the story, look at what you have being printed.

System.out.println(randGen.nextInt(die));

should be

System.out.println(die);

CodePudding user response:

int die = (int)(Math.random() * 5) 1;

Try this instead

Math random will create a random double number from 0.0 to 1.0, cast it to an int since you dont want doubles for a die. Multiply by 5 to increase the range from 0 to 5, then add 1 to the result to return values from 1-6

CodePudding user response:

You can instead use Math.random() method:

Like this:

int max=7;
int min=1;
int ran=(int)(Math.random())*(max-min)) min;

/*
Math.random() will generate a random number between 7 and 1, 
but if it generates 7 and adds 1 then it will succeed the 
max range, that's why it's ((max-min) min)
*/
    
  •  Tags:  
  • java
  • Related