public class RanNumGen5 {
public static void main(String[] args) {
System.out.println(rAndNum(1, 101));
System.out.println(rAndNum(1, 101));
System.out.println(rAndNum(1, 101));
System.out.println(rAndNum(1, 101));
System.out.println(rAndNum(1, 101));
}
static int rAndNum(int min, int max) {
int n = (int) (Math.random() * (max - min)) + min;
return n;
}
}
This above code is working to generate 5 different numbers between 1 and 100
I am struggling to print out of the 5 randomly generated numbers which is Min and which is Max. ex. random numbers 3, 10, 2 , 9 ,12 Min = 2 max = 12
I’ve tried these codes in order to accomplished that with no success.
System.out.println(rAndNum min, max)
System.out.println(int max, min)
I keep getting error messages such as ‘;’ expected/class expected/not a statement.
Using IntelliJ IDEA Community Edition 2023.2
Any advice would be greatly appreciated.
Stephanie Adams is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
12
You can always use this approach:
public class Main {
public static void main(String[] args) {
int max = Integer.MIN_VALUE, min = Integer.MAX_VALUE;
int temp;
for(int i=0; i<5 ; i++) {
temp = rAndNum(1, 101);
System.out.println(temp);
if(temp > max) {
max = temp;
}
if(temp < min) {
min = temp;
}
}
System.out.println("max : " + max + "t min : " + min );
}
static int rAndNum(int min, int max) {
int n = (int) (Math.random() * (max - min)) + min;
return n;
}
}
We use a temporary variable, temp, to store the randomly generated value. We then compare this value to the current max and min values, updating them as necessary. The getRandomNumber method generates a random number between the specified minimum and maximum values. After the loop, we print the maximum and minimum values found.
Nassim Ouali is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
Just like Math.random()
,the Math
class has methods for min
and max
.
public class RanNumGen5 {
public static void main(String[] args) {
int max = Integer.MIN_VALUE, min = Integer.MAX_VALUE;
for(int i=0; i<5 ; i++) {
int rand = rAndNum(1, 101);
System.out.println(rand);
max = Math.max(max,rand);
min = Math.min(min,rand);
}
System.out.printf("Min = %d, Max = %d%n", min, max);
}
static int rAndNum(int min, int max) {
int n = (int) (Math.random() * (max - min)) + min;
return n;
}
}
prints
19
58
95
59
63
Min = 19, Max = 95
Following my comment here would give you:
import java.util.concurrent.ThreadLocalRandom;
import java.util.IntSummaryStatistics;
public class MinMax {
public static void main(String[] args) throws Exception {
IntSummaryStatistics ss = ThreadLocalRandom.current().ints(5, 1, 101).summaryStatistics();
System.out.printf("Min was %d%n", ss.getMin());
System.out.printf("Max was %d%n", ss.getMax());
}
}