Jon..
Jon..

Reputation: 440

How to Create a 2D array of characters in JAVA

char [][]grid1 = {{'O','O','O','O','O','O'},
                  {'O','O','X','X','O','O'},
                  {'O','O','O','O','X','O'},
                  {'O','O','O','O','O','X'},
                };

How will I create a 2D char array shown above. I've done using scan.next(), which creates an array of Strings and not char as next() takes input as String.

Scanner scan = new Scanner(System.in);
for (int i = 0; i < 4; i++) {
    for (int j = 0; j < 6; j++) {
        grid[i][j] = scan.next();
        }
    }

Upvotes: 0

Views: 1042

Answers (2)

Gourav
Gourav

Reputation: 35

you can take input as a string and take the first character of it

       scan.next().charAt(0);

Upvotes: 1

Raju Sharma
Raju Sharma

Reputation: 2516

You can do it by below some way:

1) Convert string to character array and get first one.

scan.next().toCharArray()[0]

2) Or find a character at 0th position of string input.

scan.next().charAt(0);

Upvotes: 3

Related Questions