Bailey507 Bailey507 - 2 months ago 6
Java Question

Math.random into an array and then printing array into 10 lines of 10

So I am just trying to figure out a way of putting randomly generated numbers into an array list. I am also trying to just put 10 numbers on a line for 10 lines for a total of 100 numbers printed out.

This is what I have tried:

import java.util.*;
public class Part1 {

public static void main(String[]args){

int[] list = new int[100];

for(int j=0; j<9; j++){
System.out.println("");
for(int g=0; g<9; g++){

for(int i=0; i<list.length; i++){

int rand = (int )(Math.random() * 500 + 1);

System.out.print(rand + " ");
}
}
}
}
}


This is the closest I think I have come to getting it some what right

but here is another one I had tried:

import java.util.*;
public class Part1 {

public static void main(String[]args){

int[] list = new int[100];

for(int i=0; i<list.length; i++){

int rand = (int )(Math.random() * 500 + 1);


for(int j=0; j<9; j++){
System.out.println(rand + " ");
for(int g=0; g<9; g++){
System.out.print("");
}
}
}
}
}


Just trying to understand how to put these random numbers into an array and then being able to print the numbers out into lines of 10. Thanks for hint and/or help in advanced.

Answer

Using a one-dimensional array:

Random rand = new Random();
int[] list = new int[100];
int count = 1;

for (int i = 0; i < list.length; i++)
{
    list[i] =  rand.nextInt(500) + 1; 

    // check if you're at the 10th number in the line
    if (count % 10 > 0) System.out.print(list[i] + " "); // print on this line
    else System.out.println(list[i] + " "); // print on a new line
    count++;
}

Using a two-dimesional array (recommended):

    Random rand = new Random();
    int[][] list = new int[10][10];

    for (int r = 0; r < list.length; r++)
    {
        for (int c = 0; c < list[r].length; c++)
        {
            list[r][c] =  rand.nextInt(500) + 1;
            System.out.print(list[r][c] + " "); // print on this line
        }
        // this occurs when you're done displaying each row, so skip a line.
        System.out.println();
    }

Using an ArrayList:

Random rand = new Random();
List<Integer> list = new ArrayList<Integer>();
int count = 1;

for (int i = 0; i < 100; i++)
{
    list.add(rand.nextInt(500) + 1); 

    // check if you're at the 10th number in the line
    if (count % 10 > 0) System.out.print(list.get(i) + " "); // print on this line
    else System.out.println(list.get(i) + " "); // print on a new line
    count++;
}