Generate Random Number in Java in a Range

In this instructional exercise, I will show you how to produce an arbitrary number in Java in a range.

There are two different ways by which Java irregular number can be produced. The primary route is to utilize nextInt() technique for java.util.Random class and the second path are to utilize an arbitrary() strategy for java.lang.Math class.

Underneath I have shared one model for each.

Produce Random Number in Java in a Range java

java.util.Random

The nextInt() technique creates an irregular number in a range. Underneath model will create irregular number in the middle of 1 and 10. Here 1 is inclusive and 10 is elite.

package com;
 
import java.util.Random;
 
public class RandomNumber{
	public static void main(String args[]){
		Random random=new Random();		
 
		//Generate random number between 1(inclusive) and 10(exclusive)
		for(int i=0;i<5;++i){
			System.out.println("Random Number in Java: "+random.nextInt(10));			
		}
	}
}

Output

Generate Random Number in Java in a Range

java.lang.Math

The irregular() strategy produces an arbitrary number in the middle of 0.0 and 1.0. Here 0.0 is inclusive and 1.0 is restrictive. In the underneath model, I have increased the outcome with 10 and typecasting it into int to get an irregular number in the middle of 1 and 10.

package com;
 
public class RandomNumber{
	public static void main(String args[]){
		int random;
		
		//Generate random number in between 1(inclusive) and 10(exclusive)
		for(int i=0;i<5;++i){
			random=(int)(Math.random()*10);			
			System.out.println("Java Random Number: "+random);
		}
	}
}

Output

Generate Random Number in Java in a Range

Leave a Comment

error: Alert: Content is protected!!