Hitesh Sadana
Hitesh Sadana

Reputation: 9

How to Print this in a Format

This is my code

class demo {
    public static void main(String args[]) {
        String[] str = {
                "MC", "MR", "MS", "M+", "M-", "BACK", "CE", "C", "+-", "ROOT",
                "7", "8", "9", "%", "4", "5", "6", "*", "1/X", "1", "2", "3",
                "-", "=", "0", ".", "+"};
        int z = 0;
        for (int i = 0; i < str.length; i++) {
            for (int j = 0; j < 4; j++) {
                System.out.print(str[z] + " ");
                z++;
            }
            System.out.println();
        }
    }
}

now, what i want is to print them all in a pattern of four columns in one row, but somehow i'm facing ArrayOutOfBoundException in this logic, please tell me if there is any improvement i can do in this code. Thanks in advance

Upvotes: 0

Views: 67

Answers (1)

Adam
Adam

Reputation: 36743

You could tackle this differently. Just print newline after every 4th value

for (int i = 0; i < str.length; i++) {
    System.out.print(String.format("%6s", str[i]));
    if (i % 4 == 3) {
        System.out.println();
    }
}

Output

MC    MR    MS    M+
M-  BACK    CE     C
+-  ROOT     7     8
 9     %     4     5
 6     *   1/X     1
 2     3     -     =
 0     .     +

Upvotes: 2

Related Questions