简体   繁体   中英

Populating a 2D array with char inputs from a text file

I want take this text

C BAB

BNOD

MDEE

and populate a 2D array. I can print out the array with this code, but it is empty as I don't know what to put in the line I commented out. So it just prints out [[, , , , ],[, , , , ],[, , , , ]] as I already got the size of the array.

char[][] wordMatrix = new char[m][n];
            while(scan.hasNext()) {
                for(int i = 0; i < wordMatrix.length;i++) {
                    String[] line = scan.nextLine().trim().split(" ");
                    for (int j = 0; j <line.length;j++) {
                        //wordMatrix[i][j]= Char.parseChar(line[j]);        
                    }//end j for loop
                }//end i for loop   
                System.out.println(Arrays.deepToString(wordMatrix));
            }//end while loop

When you do add something to the array make certain it is a character and not a String. This is a solution using a String array. You can adapt it to using a Scanner.

  • String.charAt() gets the character at the specified index. In this case 0 .
  • \\s+ splits on one or more white space characters.
String[] s = { "C B A B", "B N O D", "M D E E" };

int m = 3;
int n = 4;
char[][] wordMatrix = new char[m][n];
for (int i = 0; i < s.length; i++) {
    String[] line = s[i].trim().split("\\s+");
    for (int j = 0; j < line.length; j++) {
        wordMatrix[i][j] = line[j].charAt(0);
    } // end j for loop
} // end i for loop
System.out.println(Arrays.deepToString(wordMatrix));

prints

[[C, B, A, B], [B, N, O, D], [M, D, E, E]]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM