2

So I am trying to get my code to get a random number generation based off what the user inputs. and my current statement doesnt generate the proper range.

  secretNum = low + (int)(Math.random()* max);

Where low is the lowest part of the range, and high is the highest. For example. if low was 5 and high was 10, would this generate a range from 1-50? (5*10).

trevor
  • 21
  • 2

2 Answers2

1

I'd use a Random object for this.

You create it like this:

Random r = new Random(); 

And then from there, it is very easy to use. For a random int from 0 (inclusive) to 50 (exclusive), just do:

int randomNumber = r.nextInt(50);

I think it makes all of this much easier for you. If the user inputs 10 and 140, then you do something like this:

int lowest = 10;
int highest = 140;
int randomMax = 140-10;
int randomNumber = r.nextInt(randomMax) + 10;

It's probably the easiest way to do this.

Alex K
  • 8,269
  • 9
  • 39
  • 57
1

You save your user input in the variable in:

String in = sc.nextLine();

Then you create a instance of java.util.Random with the seed being a hash of the input:

Random r = new Random(in.hashCode());

int randomNumber = r.nextInt();

If you want to generate a random number between with a maximum and a minimum see this Question Or this one but then you need to convert c++ into java:

C++:

output = min + (rand() % (int)(max - min + 1))

Java:

output = min + (r.nextInt() % (max - min + 1))

You can also use r.nextInt(max) if you only need a maximum.

Note: For cryptographically secure random numbers use an instance of SecureRandom

Ma_124
  • 45
  • 1
  • 11