Java Collection How to - Generate random number array within a range and get min and max value








Question

We would like to know how to generate random number array within a range and get min and max value.

Answer

import java.util.Random;
/*  w w w  .ja  v  a  2  s. co m*/
public class Main {

  public static void main(String[] args) {
    int[] a = new int[10];
    
    int min = Integer.MAX_VALUE;
    int max = Integer.MIN_VALUE;

    for (int b = 0; b < a.length; b++) {
      a[b] = new Random().nextInt(100);
    }
    
    for (int b = 0; b < a.length; b++) {
      if (a[b] < min)
        min = a[b];
      if (a[b] > max)
        max = a[b];
    }
    System.out.println("Min is: " + min + " " + "Max is: " + max);
  }
}

The code above generates the following result.