문제

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