How to print the following images using a 2D array?

Viewed 118

I am trying to use 2D array to print an image, but it is wrong. How can I fix this?

int n = 4;
int m = 6;
String num[][] = new String[n][m];

System.out.println("Bài 1c : ");
for (int i = 0; i < n; i++) {
    for (int j = 0; j < m; j++) {
        if (i == 0 || (i % 2 != 0 && j % 2 != 0)
                || (i % 2 == 0 && j % 2 == 0) || i != n - 1) {
            System.out.print(num[i][j] = "A");
        } else {
            System.out.print("B");
        }
    }
    System.out.println();
}

The output should be:

AAAAAA
BABABA
ABABAB
BBBBBB

Any help would be great!

4 Answers

Hey welcome to Stackoverflow!

While reading your question, this is the best solution I could think of:

System.out.println(Arrays.deepToString(num).replace("], ", "]\n"));

By passing in the 2D array, num, it should convert it to a string and prints it out in separate lines

Make sure to import java utils using this snippet:

import java.util.*;

Hope that helped!

If this solution helped, feel free to accept this answer!

You can split the compound if condition into a chain of if else statements for clarity:

int n = 4, m = 6;
for (int i = 0; i < n; i++) {
    for (int j = 0; j < m; j++) {
        // first row
        if (i == 0)
            System.out.print("A");
        // last row
        else if (i == n - 1)
            System.out.print("B");
        // intermediate rows
        else if ((i + j) % 2 == 0)
            System.out.print("A");
        else
            System.out.print("B");
    }
    System.out.println();
}

Output:

AAAAAA
BABABA
ABABAB
BBBBBB

Your description didn't say anything about how to generate the 2D array.

Why not something simple like this?

public static void main(String[] args) {
    String data[][] = new String[][] {
        {"A", "A", "A", "A", "A", "A"},
        {"B", "A", "B", "A", "B", "A"},
        {"A", "B", "A", "B", "A", "B"},
        {"B", "B", "B", "B", "B", "B"}
    };

    for(int r = 0; r < data.length; r++) {
        for(int c = 0; c < data[r].length; c++) {
            System.out.print(data[r][c]);
        }
        System.out.println();
    }
}

I'd use bitwise masks:

public static void main(String []args){
    for (int t: new int[]{0,42,21,63})
        System.out.println(String.format("%1$6s", Integer.toBinaryString(t)).replace(' ', '0').replace('0', 'A').replace('1', 'B'));
 }
Related