Home > Back-end >  How to create a 2D array using linear data
How to create a 2D array using linear data

Time:09-27

I have this issue where I am trying to create a 5x5 grid of values.

this is what my code currently looks like

public class a {
public static void main(String[] args)
{

    int[][] arr ={ { 9, 15, 4, 10, 7, 26, 30, 18, 24, 21, 32, 39, 42, 37, 58, 21, 49, 56, 50, 74, 65, 75, 71, 72 },
    { 12, 3, 7, 6, 11, 28, 24, 25, 22, 19, 31, 35, 45, 37, 52, 57, 56, 57, 53, 62, 66, 67, 72, 75 },
    { 4, 8, 5, 2, 13, 25, 27, 22, 26, 18, 36, 33, 34, 44, 50, 59, 48, 58, 46, 74, 71, 73, 70, 66 },
    { 11, 3, 7, 6, 12, 28, 24, 25, 22, 19, 31, 35, 45, 37, 52, 57, 56, 50, 53, 62, 66, 67, 72, 75 },
    { 9, 15, 4, 10, 7, 26, 30, 18, 24, 21, 32, 39, 42, 37, 58, 51, 49, 56, 50, 74, 65, 75, 71, 72 },
    { 10, 5, 12, 7, 2, 26, 24, 18, 29, 21, 33, 40, 43, 32, 49, 60, 57, 46, 56, 64, 67, 72, 62, 65 },
    { 7, 8, 6, 14, 9, 27, 16, 23, 25, 21, 44, 37, 45, 34, 53, 52, 60, 56, 48, 73, 66, 65, 74, 62 },
    { 4, 2, 13, 15, 6, 19, 24, 22, 26, 18, 33, 43, 34, 32, 55, 50, 58, 59, 46, 70, 73, 68, 64, 71 },
    { 5, 13, 7, 12, 10, 29, 19, 23, 26, 30, 41, 36, 40, 35, 51, 54, 56, 48, 53, 71, 61, 66, 69, 74 },
    { 5, 11, 9, 1, 2, 25, 16, 28, 20, 19, 39, 40, 44, 42, 55, 58, 54, 53, 60, 72, 67, 70, 61, 71 },
    { 6, 7, 11, 3, 4, 17, 18, 25, 24, 20, 38, 42, 33, 41, 48, 54, 52, 57, 46, 66, 63, 69, 64, 61 } };
;

    for (int i = 0; i < 1; i  )
        for (int j = 0; j < 5; j  )
            System.out.println(arr[i][j] );
}

and the output looks like this:

9
15
4
10
7

how would I alter this for the output to look like

9   26  32  58  74
15  30  39  21  65
4   18  FR  49  75
10  24  42  56  71
7   21  37  50  72

after the first 12 numbers I want FR to appear and then display the last 12 numbers

CodePudding user response:

Hi, in your first loop code,the value of i less than '1', so always print a[0][j].

 int k = 0;
    for (int i = 0; i < 5; i  ) {
        for (int j = 0; j < 5; j  ) {
            if (k == 12) {
                System.out.print("FR" " ");
            }else {
                System.out.print(arr[i][j]   " ");
            }
            k  ;
        }

        System.out.println();
    }

CodePudding user response:

Try this.

int center = 12;
for (int i = 0; i < 5;   i) {
    for (int j = i; j < i   25; j  = 5) {
        if (j == center)
            System.out.printf("FR ");
        else
            System.out.printf("%-3d", arr[0][j <= center ? j : j - 1]);
    }
    System.out.println();
}

output:

9  26 32 58 74 
15 30 39 21 65 
4  18 FR 49 75 
10 24 42 56 71 
7  21 37 50 72 
  • Related