How to get a random between 1 - 100 from randDoubl

2019-02-16 12:18发布

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?

标签: java random
4条回答
我只想做你的唯一
2楼-- · 2019-02-16 12:40
    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);
查看更多
放荡不羁爱自由
3楼-- · 2019-02-16 12:43

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楼-- · 2019-02-16 12:45

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.

查看更多
ら.Afraid
5楼-- · 2019-02-16 12:49

or

Random r = new Random();
int randomInt = r.nextInt(100) + 1;
查看更多
登录 后发表回答