Reputation: 11
I'm trying to make a two-dimensional array that generates a random number from 0-50. It works but it doesn't generate a 3 by 5 layout with columns and rows.
I've tried changing around the i and the j and using different variables.
/**
* Constructor for objects of class GenerateLithium
*/
public GenerateLithium()
{
randomGenerator = new Random();
}
public void generateSample()
{
for (int i = 0; i < 5; i++)
{
for (int j = 0; j < 3; j++)
{
tray[i][j] = i * j;
tray[i][j] = grading++;
grading = randomGenerator.nextInt(50);
System.out.print(" ");
}
}
}
public void printTray()
{
for (int i = 0; i < 5; i++)
{
for (int j = 0; j < 3; j++)
{
System.out.println(tray[i][j] + " ");
}
System.out.println("");
}
}
Result Now:
45
22
11
23
1
35
45
43
22
13
15
3
0
16
42
Expected Result:
45
22
11
23
1
35
45
43
22
13
15
3
0
16
42
Upvotes: 0
Views: 1099
Reputation: 326
public void printTray()
{
for (int i = 0; i < 5; i++)
{
for (int j = 0; j < 3; j++)
{
System.out.print(tray[i][j] + "/t ");
}
System.out.println("");
}
}
Upvotes: 1
Reputation: 1369
This is a full GenerateLithium class that prints a 3 x 5 table.
class GenerateLithium{
Random randomGenerator;
int[][] tray = new int[5][3];
int grading;
public GenerateLithium() {
randomGenerator = new Random();
}
public static void main(String args[]) throws UnsupportedEncodingException {
GenerateLithium m = new GenerateLithium();
m.generateSample();
m.printTray();
}
public void generateSample() {
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 3; j++) {
tray[i][j] = i * j;
tray[i][j] = grading++;
grading = randomGenerator.nextInt(50);
}
}
}
public void printTray() {
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 3; j++) {
System.out.print(tray[i][j] + "\t");
}
System.out.println();
}
}
}
Result:
0 8 14
29 33 20
18 37 10
33 21 2
8 45 29
Upvotes: 0
Reputation: 793
You can do this to show output of array 2D as Grid layout:
public void printTray()
{
for (int[] x : tray) {
System.out.println(Arrays.toString(x));
}
}
Upvotes: 0
Reputation: 779
Replace the first System.out.println
with System.out.print
inside printTray()
method.
Upvotes: 0