Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to generate positive and negative numbers in Java [duplicate]

Tags:

java

random

math

Possible Duplicate:
How to generate random positive and negative numbers in java

Hello I am trying to create a method in Java to create negative and positive values in Java.

the problem is that I don't know how to get this programmed but I do know the logic.. here is what I tought it should be

 Random generator = new Random();

 for (int i = 0; i < 21; i++)
 {
       System.out.print(generator.nextInt(100) + 1);
       System.out.println();
 } 

but with the code above I get only positive values and I need values between -100 and 100 but how can I accomplish something like that?

like image 611
Reshad Avatar asked Oct 19 '12 11:10

Reshad


People also ask

How do you randomly generate a negative number in Java?

The correct code is int rand = new Random(). nextInt((30 - 20) + 1) + 20; .

Can double have negative values Java?

One of the tricky parts of this question is that Java has multiple data types to support numbers like byte, short, char, int, long, float, and double, out of those all are signed except char, which can not represent negative numbers.

How do you generate positive random numbers in Java?

The nextDouble() and nextFloat() method generates random value between 0.0 and 1.0. The nextInt(int bound) method accepts a parameter bound (upper) that must be positive. It generates a random number in the range 0 to bound-1.


2 Answers

You can use:

Random generator = new Random();
int val = 100 - generator.nextInt(201);

Or, as JoachimSauer suggested in the comments:

int val = generator.nextInt(201) - 100;
like image 129
Pablo Santa Cruz Avatar answered Nov 15 '22 08:11

Pablo Santa Cruz


The general formula is

int val = rand.nextInt(max - min + 1) + min;

Note that min and max can be negative. (max > min)

like image 21
Peter Lawrey Avatar answered Nov 15 '22 07:11

Peter Lawrey