Yahoo Answers is shutting down on May 4th, 2021 (Eastern Time) and beginning April 20th, 2021 (Eastern Time) the Yahoo Answers website will be in read-only mode. There will be no changes to other Yahoo properties or services, or your Yahoo account. You can find more information about the Yahoo Answers shutdown and how to download your data on this help page.

Question about making Random Numbers in Java?

I'm making a number guessing game for a school project. I need my "secret number" to be a number from 1 - 100 and rather than hard coding in the number I wanted to make a random number but I don't know how. Any help?

3 Answers

Relevance
  • McFate
    Lv 7
    9 years ago
    Favorite Answer

    Math.random() returns a random number that is between 0 and 1 (greater than or equal to zero, strictly less than 1).

    If you want X different integers, you multiply Math.random() times X, and truncate it to an integer. So...

    (int) (Math.random() * 100)

    ... is a number from 0 to 99. Add 1 to that, and you get a number between 1 and 100, inclusive:

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

    @M

  • 9 years ago

    If you want an int between 1 and 100, inclusive then use the

    Random

    class.

    import java.util.Random;

    Random randObj = new Random(); // the object

    int randNum = randObj.nextInt(100) + 1;

  • 9 years ago

    import java.util.Random;

    /** Generate 10 random integers in the range 0..99. */

    public final class RandomInteger {

    public static final void main(String... aArgs){

    log("Generating 10 random integers in range 0..99.");

    //note a single Random object is reused here

    Random randomGenerator = new Random();

    for (int idx = 1; idx <= 10; ++idx){

    int randomInt = randomGenerator.nextInt(100);

    log("Generated : " + randomInt);

    }

    log("Done.");

    }

    private static void log(String aMessage){

    System.out.println(aMessage);

    }

    }

    if u want to learn more then go to:

    http://www.javapractices.com/topic/TopicAction.do?...

Still have questions? Get your answers by asking now.