m2pixel
m2pixel

Reputation: 1

Java two dimensional output matrix

i want you to help me, this is my code:

public static void main(String[]args)
{
        Scanner input = new Scanner(System.in);

        System.out.print("Type your text: ");
        String text = input.nextLine();

        int counter = text.length();
        if(text.length()> 16)
        {
            System.out.println("Error: input text is greater than 16 characters");
            System.exit(0);
        }
        else
        {
            while(counter < 16)
            {
                text = text.concat("x");
                counter++;
            }

            char[][] k = new char[4][4];

            //int push = 0;

                                int push;

                                for (int i = 0; i < k.length; i++) {
                                    push = i;
                                    for (int j = 0; j < k[i].length; j++) {
                                        k[i][j] = text.charAt(push);
                                        System.out.print(k[i][j] + " ");
                                        push = push + 4;
                                    }
                                    System.out.println();                
                                }
        }

}

Now when i type: abcdefghijklmn , the output is:

a e i m
b f j n
c g k x
d h l x

this is perfect, when i print it looks like matrix. But now i have to print in other way:

aeim, bfjn, cgkx, dhlx

not as matrix but in line (with comma)

Upvotes: 0

Views: 107

Answers (3)

MaineCoder
MaineCoder

Reputation: 159

Add this at the end, after the first set of nested for loops:

for (int j = 0; j < k[i].length; j++) {
     for (int i = 0; i < k.length; i++) {
              if (j == k[i].length - 1 && i == k.length - 1)
                   System.out.print(k[i][j] + ".");
              else
                   System.out.print(k[i][j] + ", ");
     }
}

The way that k is currently assigned values, it will print in this order:

aeim, bfjn, cgkx, dhlx

By reversing the nested for loops and modifying the print command, it will print:

a, b, c, d, e, f, g, h, i, j, k, l, m, n, x, x.

This is, of course, assuming that you want to print the matrix and the list. If not, then reverse the initial loop and change the way the values are assigned.

Upvotes: 0

Qadir Hussain
Qadir Hussain

Reputation: 1263

Just replace System.out.println(); with System.out.print(", ");

Upvotes: 1

Mahmoud Hashim
Mahmoud Hashim

Reputation: 550

just replace System.out.println() with System.out.print(", "); you don't need any condition and don't concat the character with a space, hope it works

Upvotes: 1

Related Questions