How to get a random between 1 - 100 from randDoubl

2019-02-16 12:23发布

问题:

Okay, I'm still fairly new to Java. We've been given an assisgnment to create a game where you have to guess a random integer that the computer had generated. The problem is that our lecturer is insisting that we use:

double randNumber = Math.random();

And then translate that into an random integer that accepts 1 - 100 inclusive. I'm a bit at a loss. What I have so far is this:

//Create random number 0 - 99
double randNumber = Math.random();
d = randNumber * 100;

//Type cast double to int
int randomInt = (int)d;

However, the random the lingering problem of the random double is that 0 is a possibility while 100 is not. I want to alter that so that 0 is not a possible answer and 100 is. Help?

回答1:

You're almost there. Just add 1 to the result:

int randomInt = (int)d + 1;

This will "shift" your range to 1 - 100 instead of 0 - 99.



回答2:

or

Random r = new Random();
int randomInt = r.nextInt(100) + 1;


回答3:

Here is a clean and working way to do it, with range checks! Enjoy.

public double randDouble(double bound1, double bound2) {
        //make sure bound2> bound1
        double min = Math.min(bound1, bound2);
        double max = Math.max(bound1, bound2);
        //math.random gives random number from 0 to 1
        return min + (Math.random() * (max - min));
    }

//Later just call:

randDouble(1,100)
//example result:
//56.736451234


回答4:

    double random = Math.random();

    double x = random*100;

    int y = (int)x + 1; //Add 1 to change the range to 1 - 100 instead of 0 - 99

    System.out.println("Random Number :");

    System.out.println(y);


标签: java random