int min = 20;
int max= 150;
System.out.println("Random value from " min " to " max ":");
for(int i = 0; i<2; i ) {
int random_int = (int)Math.floor(Math.random()*(max-min 1) min);
System.out.println(random_int);
I get two random number in the output, but I don't know how to proceed with determining the highest value in the output?
CodePudding user response:
Replace the dots by anything you want.
int a=...;
int b=...;
if (a>b) {
...
}else{
...
}
CodePudding user response:
You write both random values to the same variable: random_int
.
Thus, once you've written the second value, the first will be gone.
In order to compare them, you need to write them to different variables like random_int_1
and random_int_2
or an array.
CodePudding user response:
Declaring an int and assigning it a value in a loop will overwrite it's value on each iteration. You're treating random_int as if its a function. If you only need 2 ints, I would ditch the loop altogether. Math.max() will return the higher of 2 values. You can use Math.max() and double up your random declaration logic like this:
System.out.println(Math.max((int)Math.floor(Math.random()*(max-min 1) min),
(int)Math.floor(Math.random()*(max-min 1) min)));
Or:
Create 2 separate int variables like this:
int x = (int)Math.floor(Math.random()*(max-min 1) min);
int y = (int)Math.floor(Math.random()*(max-min 1) min);
System.out.println( Math.max(x,y) );
Or:
int x = (int)Math.floor(Math.random()*(max-min 1) min);
int y = (int)Math.floor(Math.random()*(max-min 1) min);
int z = Math.max(x,y);
System.out.println(z);