6

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?

Community
  • 1
  • 1
Reshad
  • 2,570
  • 8
  • 45
  • 86

2 Answers2

16

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;
Pablo Santa Cruz
  • 176,835
  • 32
  • 241
  • 292
10

The general formula is

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

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

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130