2

I have an assignment to populate the array with random number ranging from 0-9. Then print it out in a rectangular format. I'm already having trouble trying to put random integers in the array. Please point me in the right direction

import java.util.*;
public class ThreebyFour
{
    public static void main (String[] args)
    {
     int values[][] = new int[3][4];
     for (int i = 0; i < values.length; i++) 
     {
        for (int j = 0; j < values.length; j++) 
        {
          values[i][j] = ((int)Math.random());
         System.out.println(values[i][j]);
        }
     }
 }
}
S. Singh
  • 23
  • 1
  • 1
  • 4
  • It's printing out all zeros – S. Singh Apr 20 '16 at 19:55
  • Of course it is. What does Math.random() return? And when you cast that to an int? – stdunbar Apr 20 '16 at 19:58
  • How do I make it print 0-9 inclusive. Sorry I am very new to java and coding in general – S. Singh Apr 20 '16 at 20:01
  • See [Generating random integers in a specific range](http://stackoverflow.com/questions/363681/generating-random-integers-in-a-specific-range). – Gerold Broser Apr 20 '16 at 20:05
  • The random() call gives you numbers between 0 and 1. The `int` cast will turn them all to zeros. Leave out the `int` for yourself to see. You could multiply the result of `random()` by 10 and you'll get integers from 0 to 9. – roadrunner66 Apr 21 '16 at 00:37

2 Answers2

3

cosmetic issues in your code:

like:

values[i][j] = ((int)Math.random());

this will assign all elements to zero since the return of random value is between 0 and 1 exclusive [0, 1) and that cast to integer will return a zero..

and this:

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

the second for loop would be better if you do it counting the elements of that row... like I wrote in the comments...

i.e doing:

for (int j = 0; j < values[i].length; j++) {

fixed code:

public static void main(String[] args) {
    int values[][] = new int[3][4];
    for (int i = 0; i < values.length; i++) {
        // do the for in the row according to the column size
        for (int j = 0; j < values[i].length; j++) {
            // multiple the random by 10 and then cast to in
            values[i][j] = ((int) (Math.random() * 10));
            System.out.print(values[i][j]);
        }
        // add a new line
        System.out.println();
    }
    System.out.println("Done");
}
ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97
0

You could do Math.round (Math.random() * 10). I suggest reading the javadoc and understanding what the random() method does.

https://docs.oracle.com/javase/7/docs/api/java/lang/Math.html#random()

Bajal
  • 5,487
  • 3
  • 20
  • 25