how-to

Math

How to generate random int value from interval

For working with Random class you need to use:

import java.util.Random;

When you need to generate random int value, for example in interval 1..9, use this code:

Random random = new Random();
        
for ( int i = 1; i <= 5; i++ ) {
  /* generate 1..9 int value */
  int value = random.nextInt( 9 ) + 1;      
  System.out.println( value );     
}

The code generates 5 random int values, for example:

8
2
6
9
9
Info: Random.nextInt( value ) returns value in interval 0..value.