Top community members
All Wiki Articles Create Wiki Article

Welcome to Dirask IT community! ā¤ šŸ’»
We are community of people that helps each other.

If you are beginner in IT field, you are more then welcome to ask questions, it will help you to learn faster. We are here to help you.

We are always beginner in something, we just need to remember it along the way.

there are no wrong questions - Ask Question

Java - random integer number in range with exclusive max value example

0 contributions
4 points

In this short article we want to show how in Java randomizeĀ integer numberĀ in range with exclusive max value.

1. Custom random methodĀ examples

package com.dirask.examples;

public class RandomUtil {
	
	public static int randomize() throws Exception {
		return randomize(Integer.MAX_VALUE);
	}
	
	public static int randomize(int max) throws Exception {
		return randomize(0, max);
	}
	
	public static int randomize(int min, int max) throws Exception {
	  	if(min > max - 1) {
	    	throw new Exception("Incorrect arguments.");
	    }
	    return (int) (min + (max - min) * Math.random());
	}
}

Usage example:

package com.dirask.examples;

public class Program {

    public static void main(String[] args) throws Exception {

        System.out.println( RandomUtil.randomize() );         //  5547382624322139
        System.out.println( RandomUtil.randomize( 5 ) );      //  3
        System.out.println( RandomUtil.randomize( 10, 80 ) ); //  62
        System.out.println( RandomUtil.randomize(-50, 50 ) ); // -8
    }   
}

Ā 

0 contributions

Checkout latest Findings & News:

Checkout latest questions:

Checkout latest wiki articles:

Hey šŸ‘‹
Would you like to know what we do?
  • Dirask is IT community, where we share coding knowledge and help each other to solve coding problems.
  • We welcome everyone,
    no matter what the experience,
    no matter how basic the question is,
    this community will help you.
Read more