0

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.

2
Contributors
3
Replies
4
Views
6 Years
Discussion Span
Last Post by tong1
0

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 by tong1: n/a

0

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.

0

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 by tong1: n/a

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.