I've searched high and low for the answer to this and can't see how I'm doing it wrong, I've tried several different ways of coding it but it always goes outside the range I'm looking for. (90 - 180 inclusive).

Can anyone shed some light on the code below???

Random rnd = new Random();
int time = rnd.nextInt(91) + 90;

Thanks for any support offered...


    /**
 * Randomly generates a number between 90-180 inclusive and sets the random number as an     argument to a message-send for each of the 
 * Runner objects in runnersList.
 */
public void runMarathon()
{
   for (Runner r : runnersList)
   {
      Random rnd = new Random();
      int time = rnd.nextInt(91) + 90;
      r.setTime(time);
   }
}
有帮助吗?

解决方案

This function will help you to do what you need


private int randInt(int min, int max) {

        return new Random().nextInt((max - min) + 1) + min;
}

just give min and max values as parametres to the function and you will get a random value between the range you specified ;)

其他提示

A key principal in software development is reuse. So to do this, you can use "http://commons.apache.org/proper/commons-lang/javadocs/api-3.3/org/apache/commons/lang3/RandomUtils.html#nextInt(int, int)" instead of reinventing the wheel.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top