Solved

Posted on 2011-04-28

I am trying to initialize an array with random numbers. Can't figure out why it's putting out zero's. Any ideas??

Lynn

Lynn

```
int numItems = 20;
int[] array = new int[numItems];
for(int j = 0;j< array.length; j++){
//array[j] = (int)Math.random() * 9;
System.out.println("Random num: " + (int)Math.random() * 9);
}
```

22 Comments

int numItems = 20;

int[] array = new int[numItems];

for(int j = 0;j< array.length; j++){

array[j] = (int)Math.random() * 9;

System.out.println("Random

}

int numItems = 20;

int[] array = new int[numItems];

for(int j = 0;j< array.length; j++){

array[j] = (int)(Math.random() * 9);

System.out.println("Random

}

int numItems = 20;

int[] array = new int[numItems];

for(int j = 0;j< array.length; j++){

array[j] = (int)(Math.random() * 9);

System.out.println("Random

}

What do I need to do to come up with random integers?

the rounding has already occurred before that. its rounding the random to zero

try my first comment

when you cast it integer it always bcekl=omes zzero

Multiply firts then cast and it will be OK

of that number - it will be zero

if you first multiply by 10 or by 100 then the floor will be integer and you can

cast and get integer number

which is what I suggested in my first comment.

Why accept a comment that repeats what had already been posted?

It's nothing to do with rounding:

System.out.println("Random

You cast the result of random() to an int, which will result in zero - game over.

What you need is the following, which will cast the result of random() * 9 to an int

System.out.println("Random

( http:#35488970 )

>>

due to rounding

System.out.println("Random

>>

The problem is due to

a. casting

b. precedence

The answer had been assigned correctly.

This is the code from taken from ID:35488981:

```
int numItems = 20;
int[] array = new int[numItems];
for(int j = 0;j< array.length; j++){
array[j] = (int)(Math.random() * 9);
System.out.println("Random num: " + array[j]);
}
```

THis is the output of random numbers (by no means all zeros):

```
Random num: 5
Random num: 2
Random num: 4
Random num: 8
Random num: 0
Random num: 3
Random num: 3
Random num: 8
Random num: 4
Random num: 3
Random num: 5
Random num: 7
Random num: 8
Random num: 1
Random num: 1
Random num: 5
Random num: 6
Random num: 5
Random num: 0
Random num: 5
```

ID:35488999 also provided correct explanation

which does exactly the same as what I had already posted

Title | # Comments | Views | Activity |
---|---|---|---|

JKS to store upstart data | 2 | 51 | |

Fix45 challenge | 15 | 66 | |

Enhanced For loop vs ForEach Loop | 4 | 42 | |

network + | 7 | 58 |

This tutorial covers a step-by-step guide to install VisualVM launcher in eclipse.

Join the community of 500,000 technology professionals and ask your questions.

Connect with top rated Experts

**18** Experts available now in Live!