-1

I want to print 10 random numbers from -100 to 100, but my code below always print negitive number. I did not get any answer for this. How to do this ?

import java.util.Random;
public class VectorAndList {
public static void main(String arg[]){
    Random random = new Random();
    int number ;
    for(int i=0;i<10;i++)
    System.out.println(number = random.nextInt(100)+ (-100)) ;
}
}
dimo414
  • 44,897
  • 17
  • 143
  • 228
topper1309
  • 151
  • 3
  • 15

2 Answers2

1

Problem is you calculate random number between 100 then you minus(100) that values thats why you received values negative only.

so change like this

Random random = new Random();
int number ;
for(int i=0;i<10;i++)
System.out.println(number = random.nextInt(201)-100) ;
sasikumar
  • 11,797
  • 2
  • 26
  • 44
1

Generate number from 0-100 and flip the sign randomly

Random rand = new Random();
int no = rand.nextBoolean() ? rand.nextInt(100) : rand.nextInt(100) * -1;
System.out.println(no);

alternatively you can use ThreadLocalRandom with negative range as well

ThreadLocalRandom random = ThreadLocalRandom.current();
for (int i = 0; i < 10; i++) {
    int no = random.nextInt(-100, 100);
    System.out.println(no);
}
Saravana
  • 12,109
  • 2
  • 37
  • 52