Anonymous
Anonymous asked in Computers & InternetProgramming & Design · 8 years ago

Proper use of Java's Math.random() function?

I have a quick question about how to use the function Math.random() properly.

Lets say I wanted to make a random number between 1 and 10, I know to do this I need to use the following code;

(int)(Math.random() * 10) + 1

Is the "+ 1" at the end is necessary seeing as I already have "(int)" at the front? And if I were to take out the "+ 1" would it create a random number between 0 and 10, instead of 1 and 10?

3 Answers

Relevance
  • 8 years ago
    Favorite Answer

    As Baatus says, if you want random ints it's better to use the random class:

    Random rand = new Random();

    int rNum = rand.nextInt(10) + 1;

    Because

    nextInt(k)

    returns 0 through k-1, inclusive. So nextInt(10) is 0-9, adding the 1 gives 1-10.

    don't forget to

    import java.util.Random;

  • ?
    Lv 5
    8 years ago

    actually .random() returns a number between 0 and 1 and is actually real. You multiply by the end of the interval and add the begining. So for example if I wanted to generate a number between 3 and 20 I would use

    Math.random() * 20 + 3

    basically it's .random() * max + min

    since it's between 0 and 1. So the 1 turns into the max and you push the 0 to wherever you need (like 1 or 3 etc.)

  • Anonymous
    8 years ago

    I always do

    Random r=new Random();

    int i= r.nextInt(10)+1;

Still have questions? Get your answers by asking now.