1

I have an array that can hold 5 integers.In the for loop I use Math.random() to fill the array with random integer values between 0 and 10 that can be positive or negative. How can I receive the negative value? Someone recommended me to multiply by -1 the formula to fill out array with positive and negative values but when I do this all my values in the array are negative. I think the problem is in this line

 int r = 0 + (int) (Math.random() * 10 *(-1));

This is the code:

 public class Random 
 {

 public static void main(String [] args) 
 { 
     int [] arr= new int[5];


     for(int k=0; k<arr.length; k++)
     {
          int r = 0 + (int) (Math.random() * 10 *(-1));
          arr[k] = r;
     }

     int j = 0;
     while(i<arr.length) {
         System.out.print(arr[i] + " ");
         j++;
     } 

 }
}


Now my output is -7 -3 -3 -5 -6

I want my output to be 7 -3 3 -5 6

user1282256
  • 183
  • 1
  • 6
  • 16
  • Try `arr[k] = r * ((Math.random() > 0.5) ? 1 : -1)` to add random to the negative/positive. Or you could move the range of the random interval (Eran's answer) – Daniel Sep 23 '14 at 11:43

3 Answers3

4

If you want numbers between -10 and 10 :

int r = (int) (Math.random() * 21) - 10;

Since Math.random() never returns 1.0, (int) (Math.random() * 21) would return integers between 0 and 20, and after substracting 10, you'll get what you want.

An alternative is to use java.util.Random :

Random rand = new Random();
int r = rand.nextInt(21) - 10;
Eran
  • 387,369
  • 54
  • 702
  • 768
0

You could produce a random number between 0 and 20 and subtract 10 from it. Doing this you wiil get a random number between -10 and +10:

int r = (int) ( Math.random() * 20 ) - 10;
Michael
  • 129
  • 1
  • 2
0

You just need to modify your code as below

    public class Random 
    {

        public static void main(String[] args) {
           int[] arr = new int[5];

            for(int k=0; k<arr.length; k++)
            {
                int r = 0 +(int)(Math.random()*10*(k % 2 == 0? 1:-1));
                arr[k] = r;
            }
            int j = 0;
            while(j<arr.length)
            {
                System.out.print(arr[j]+ " ");
                j++;

            }
            System.out.println();
        }

    }
Streuby
  • 3
  • 1
  • 4