Input/Output convert string to two dimensional char and output = matrix

emtwo

Neues Mitglied
I have written the code:
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;

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




And input is: abcdefghijklm

output is:

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

So all i want is, if i type: abcdefghijklm I want this output:
Code:
a e i m
b f j x
c g k x
d h l x
 
Try this
Java:
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();                
}
 
Zuletzt bearbeitet:
Try this
Java:
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();                
}

WOW!! Thank you bro, this is amazing. I want you to help me just one more thing.

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,but now i have to print in other way:

aeim, bfjn, cgkx, dhlx

(with comma)
 

Zurück
Oben