48502104 48502104 -4 years ago 126
Java Question

How to convert a String to a 2D char array JAVA

..4UVdaUz9Tm
nlt3YTQUYx
RCLDjoe6DV
fecFQa1xPY
WCXgDvOO2y
d7HJ5F1Ma4
VEqx6W9TVu
vrClZPrAE2
QYygVoIL82
0pdZMP7oK9
wvLSDzwbr5
HutqlJttoH
7SVyEZ6Jbv
kGekxE4Su4
71hJQWrgCy
QGLeXDio3f
4VSlLXRYTz
lX57PpnqFD
VuN1BLd3fE
Fk5VZKcVnp
cTB7SKHeTi
2N87wPnRUG
rdm193ZJwD
Z2oeIuVNfM
tAzTlO8SyQ
3nXxZtXwNz
noKPRfB8Nn
KECabCyY4c
lKOOoCNScQ
t5HImqHAQB
unlZu9J6ko
ntgN5sSCfU
ehs6NJrOiL
4726aA5KZh
EtqE4kUA01

Answer Source

You need another counter for the String offset

int offset = 0;
for (int i=0; i < row; i++) {
    for (int j=0; j < column; j++) {
        boardArray[i][j] = startConfig.charAt(offset++);
        System.out.println(boardArray[i][j]);
    }
}

or as per Tim's excellent answer, the offset can be calculated as j + i*column

For the output to match try

int offset = 0;
for (int i=0; i < row; i++) {
    for (int j=0; j < column; j++) {
        boardArray[i][j] = startConfig.charAt(offset++);
        System.out.print(boardArray[i][j]);
    }
    System.out.println ();
    // uncomment below line if you want a blank line
    // System.out.println ();
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download