aman shivhare
aman shivhare

Reputation: 334

Store a matrix in 2d char array Java

I am trying to store a matrix in java 2d char array but since I can't accept the input in char, I am trying to look for the best possible solution to store in a 2d char array.

eg. Matrix

 1112
 1912
 1892
 1234

What I tried:-

 for(int i=0; i<n; i++)
        for(int j=0; j<n; j++)
            map[i][j]=sc.next().charAt(0);

Gives wrong output. Any other suggestions?

Upvotes: 1

Views: 1823

Answers (1)

codegasmer
codegasmer

Reputation: 1468

You need to change the code to

String data = "";
int count = 0;
for (int i = 0; i < n; i++) {
    if (sc.hasNext()) {
        data = sc.next();
        count = 0;
    } else {
        break;
    }
    for (int j = 0; j < n; j++)
    map[i][j] = data.charAt(count++);
}

for loop of i and j is for generating matrix indexes and since you need to read the character you first have to read token by token then iterate over their characters the other user answer fails because the user uses j loop for both matrix and chracter reading so if on the last iteration of j ie n-1(denotes matrix length not the string length) if string length is less than n-1 you will get IndexOutOfbound Exception for in.charAt(j).

Upvotes: 1

Related Questions