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.
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.
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;
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.