Home > front end >  I would like to add char Z when looping through, to one of column in the array
I would like to add char Z when looping through, to one of column in the array

Time:08-02

I would like to add char Z when looping through, to one of column in the array.

My result is:

A B C c
D E F f 
G H I 
J K L 

but I want to:

A B* C c 
D E* F f 
G H* I 
J K* L 

Here is my code:

       char z = '*';

        char[][] marks = {
                {'A', 'B', 'C', 'c'},
                {'D', 'E', 'F','f'},
                {'G', 'H', 'I'},
                {'J', 'K', 'L'},
        };
        for (char[] x : marks) {
            for (char y : x) {
                System.out.print(y   " ");
            }
            System.out.println();
          }

CodePudding user response:

One way to do this is to keep track of the position where you want to add the z character! In your example, you're always adding it to the second column so y=1.

An Example would be something like this :

     char z = '*';
     char[][] marks = { { 'A', 'B', 'C', 'c' }, { 'D', 'E', 'F', 'f' }, { 'G', 'H', 'I' },
            { 'J', 'K', 'L' }, };
     for ( char[] x : marks) {
        int y = 0;
        while (y < x.length) {
            if (y == 1) {
                System.out.print(String.format("%c %c ", x[y], z));

            } else {
                System.out.print(String.format("%c ", x[y]));

            }
            y  ;

        }
        System.out.println();
    }

}
  • Related