0

I'm searching for an easy way to generate random numbers with a defined max and minimum, but for the purpose I need using the standard way to generate randoms complicates my code too much. The standard way being:

Random rand=new Random();
rand.nextInt(125)+1;

While I'm looking for a simpler way, something along the lines of:

Random(125,1);
Twhite1195
  • 351
  • 6
  • 17
  • 5
    Then create your own random class. – robotlos May 23 '16 at 23:50
  • I know I can do that, I'm asking if there's another way to create random numbers that I'm not aware of – Twhite1195 May 23 '16 at 23:51
  • 1
    Whats wrong with the standard way ? Why not write your own method which uses the standard way, in a format that suits you? – Alan Kavanagh May 23 '16 at 23:52
  • Why do you believe the first way is not acceptable? Your way isn't even valid Java syntax unless `Random` is a method in your class, which would then require you define that method. Just wishing for Java to have the syntax you want doesn't make it so. Random is defined the way it is for very good reasons (separate seeding from random nujmber generation). – Jim Garrison May 24 '16 at 00:10
  • I know I can make it, I was just asking if it already exists, I'm trying to learn if there is a command I'm not aware of instead of creating a method for it, which I can but I wanted to see if there was an alternate way of generating it – Twhite1195 May 24 '16 at 00:15

3 Answers3

0

This is another way, not sure you call this easy too:

(int)(Math.random()*125+1)

The other way is to define your own random class.

Hessam
  • 1,377
  • 1
  • 23
  • 45
0

You could hide all the 'complicated' code in a method and then generate your numbers using a simple random(min, max) call

Random rand = new Random();

public int random(int min, int max)
{
    return rand.nextInt(max) + min;
}

myInt = random(1, 150)
system.out.print(myInt)
Alan Kavanagh
  • 9,425
  • 7
  • 41
  • 65
0

You might need to explain better what 'complicates' means for you. Two lines of code rather than one is not more complicated if it clarifies your intent.

One thing to be aware of that can simplify things is that Java 8 gives you the option of generating a stream of random numbers within a range. This is particularly useful if you are trying to generate a collection of objects with some random value set.

For example to generate 15 random ages between 30 and 50:

List<Age> ages = random.ints(15, 30, 50)
    .map(Age::new).collect(Collectors.toList());

In some circumstances this can be clearer than traditional iteration (depending on application).

sprinter
  • 27,148
  • 6
  • 47
  • 78