Ive been trying to generate a second random number less than my first random number in every scenario, but the code keeps breaking or sometimes returning null
Random randN = new Random();
int firstNumbereasy; //declaring variables for easy mode
int secondNumbereasy;
firstNumbereasy = randN.nextInt(11); //
secondNumbereasy= randN.nextInt(firstNumbereasy-1);
CodePudding user response:
You can do it by running the following:
firstNumbereasy = randN.nextInt(MAX_RANDOM_NUM_NUMBER) 2;
secondNumbereasy= randN.nextInt(firstNumbereasy - 1);
Note that the 1st number can never by 0 as otherwise you might get an exception while trying to generate the 2nd number, and that's why you always add 1 to the result...
CodePudding user response:
The answer is in the Random.nextInt(bound) docs.
To cite:
Returns a pseudorandom, uniformly distributed int value between 0 (inclusive) and the specified value (exclusive)
And
bound - the upper bound (exclusive). Must be positive.
Parameter bound
must be strictly greater than 0. If your first nextInt()
call generaters 0
or 1
, the next bound parameter will be invalid value (0 or -1) and this results in exception.