Im wondering how do I correctly generate a random number in Java. Sometimes it gives me a negative, positive, very small range ,etc. Id like a simple formula that can give me some examples to control this better.

Thank you very much.

The class Math in the package java.lang has a static method random() which returns a double value with a positive sign, greater than or equal to 0.0 and less than 1.0.
I use this method to generate random number. For example, to generate a integer varying from 0 to 255 [0,255], one may call the method by the following code:

int a = (int) (Math.random()*256);

Please study the API for reference.

Edited 6 Years Ago by tong1: n/a

The class Math in the package java.lang has a static method random() which returns a double value with a positive sign, greater than or equal to 0.0 and less than 1.0.
I use this method to generate random number. For example, to generate a integer varying from 0 to 255 [0,255], one may call the method by the following code:

int a = (int) (Math.random()*256);

Please study the API for reference.

First, thank you for the reply.

Also, how about negative numbers? And is there a method just using:

import java.util.*;
import java.io.*;

?

Again, thank you for the help.

If you want to generate a negative random number, for example, in the range varying from -200 to -300 [-200,-300], you may write the code as follows:

import java.lang.Math;
…
int a = (int)(Math.random()*101)-300;

Edited 6 Years Ago by tong1: n/a

This article has been dead for over six months. Start a new discussion instead.