-3

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);
   }
}
Jase1985
  • 3
  • 2

2 Answers2

1

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 ;)

Mouad EL Fakir
  • 3,609
  • 2
  • 23
  • 37
  • i tried this but it still returned numbers above 180 :( – Jase1985 May 04 '14 at 22:59
  • If you put a `System.out.println()` call and print out `time`, do you still get values above 180? Or is that what you're doing? – awksp May 04 '14 at 23:01
  • No it's not possible my friend !! if you call the function like this randInt(90, 180) you will always have a value between 90 and 180 , i'm prettu sure about this – Mouad EL Fakir May 04 '14 at 23:03
  • Well I think it's there now, all sorts of things were going wrong so I reset the workspace and things seem to be behaving. I have the above function as a helper method assigning values directly to the object as an argument in the message. So far, so good. – Jase1985 May 04 '14 at 23:18
  • Massive thanks for this, too! – Jase1985 May 04 '14 at 23:19
-3

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.

jordan
  • 959
  • 7
  • 17
  • Can the downvoters please help me understand why this is downvoted or how this is different from the accepted answer? Both of these replies are giving an answer of how to do it. This approach means less of a liability, since you are using 3rd party software which means you dont have to test it. If the difference is that the accepted answer has source code that the reader can learn from and inspect, then you can do the same with this, see line 84 at http://commons.apache.org/proper/commons-lang/javadocs/api-3.3.2/src-html/org/apache/commons/lang3/RandomUtils.html. Thanks! – jordan May 05 '14 at 02:26
  • I take that back, yes let's please promote duplicating and wasting effort. – jordan May 09 '14 at 01:57