• Register

Java – Produce random numerals between 1 and 11

In this lesson, we will show case one method to produce random numbers between 1 and 11.

     I.        java.util.Random.nextInt

    Random():-method yields a pseudo-random dual form digit higher than or equivalent to 0.0 and fewer than 1.0.Moreover when this method is firstly called, it forms a only new pseudorandom-number maker, accurately as the expression new java.

    NextInt():- method of a Scanner entity reads in a sequence of numbers and alters them into an int form. It read out the letters gradually till it has assembled those that are used for one integer.Afterwards it alters them into a 32-bit  value.

 java.util.Random

This Random().nextInt(int bound) produces a random numeral from 1 (inclusive) to 11(bound).

1.1 Code chunk. For getRandomNumberInRange(1, 11), this will generates a random integer between 1 (inclusive) and 11 (inclusive).

private static int getRandomNumberInRange(int mininmum, int maximum) {

	if (minimum >= maximum) {
		throw new IllegalArgumentException("number must be greater than maximum");
	}

	Random r1 = new Random();
	return r1.nextInt((maximum - minimum) + 1) + minimum;
}

 

1.2 What is (maximum – minimum) + 1) + minimum?

Above mentioned method will produce a random digit in a range between min (inclusive) and max (inclusive).

//Random().nextInt(int bound) = Random integer from 1 (inclusive) to bound (exclusive)
 
//1. nextInt(range) = nextInt(maximum - minimum)
new Random().nextInt(5);  // [0...4] [minimum = 0, maximum = 4]
new Random().nextInt(6);  // [0...5]
new Random().nextInt(7);  // [0...6]
new Random().nextInt(8);  // [0...7]
new Random().nextInt(9);  // [0...8]
new Random().nextInt(10); // [0...9]
new Random().nextInt(11); // [0...10]
 
//2. To include the last value (max value) = (range + 1)
new Random().nextInt(5 + 1)  // [0...5] [minimum = 0, maximum = 5]
new Random().nextInt(6 + 1)  // [0...6]
new Random().nextInt(7 + 1)  // [0...7]
new Random().nextInt(8 + 1)  // [0...8]
new Random().nextInt(9 + 1)  // [0...9]
new Random().nextInt(10 + 1) // [0...10]
 
//3. To define a start value (min value) in a range
 
//   For example, the range should start from 1 = (range + 1) + min
new Random().nextInt(5 + 1)  + 1
new Random().nextInt(6 + 1)  + 1 
new Random().nextInt(7 + 1)  + 1 
new Random().nextInt(8 + 1)  + 1 
new Random().nextInt(9 + 1)  + 1 
 
// Range = (maximum - mininimum)
// So, the formula is ((maximum - minimum) + 1) + minimum

 
120 points
3