简体   繁体   中英

How do I make my two-dimensional array show horizontally as well as vertically in java?

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
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("");
    }
}

Replace the first System.out.println with System.out.print inside printTray() method.

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));
    }
}

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  

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM