Search code examples
javamultidimensional-arraytokenize

Using StringTokenizer to convert a .txt file into a 2d array


Text file(twodimension8.txt). The first line is the rows and cols separated by ','

4,6
1,2,3,4,5,6
23,55,34,89,41,72
9,27,19,56,33,82
3,65,21,66,85,11

My Code so far. uses TextFileInput class to read from a file

import java.util.*;

public class Tokens {
   public static TextFileInput myFile;
   public static StringTokenizer myTokens;
   public static int[][] twodimarr;
   public static String line;
   
 
   public static void main(String[] args) {

      myFile = new TextFileInput("twodimension8.txt");
      line = myFile.readLine();
      System.out.println("The input line is "+line);

      myTokens = new StringTokenizer(line,",");

      int row = Integer.parseInt(myTokens.nextToken());
      int col = Integer.parseInt(myTokens.nextToken());

      twodimarr = new int[row][col];

      for (int i = 0; i < row; i++) {
          line = myFile.readLine();
          for (int j = 0; j < col; j++) {
             myTokens = new StringTokenizer(line, ",");
             twodimarr[i][j] = Integer.parseInt(myTokens.nextToken());
          }
      }

      for (int i=0; i<row; i++) {
          for (int j=0; j<col;j++)
             System.out.print(twodimarr[i][j]);
          System.out.println();
    }
         
   } //main
}

The output:

111111   
232323232323
999999     
333333  

where the problem seems to be is the for loop where it trys to add it into the 2d array. I'm not sure on how I would fix this.


Solution

  • The actual bug is in this block:

          for (int i = 0; i < row; i++) {
              line = myFile.readLine();
              for (int j = 0; j < col; j++) {
                 myTokens = new StringTokenizer(line, ",");
                 twodimarr[i][j] = Integer.parseInt(myTokens.nextToken());
              }
          }
    

    myTokens should be reassigned only once per row, not at each individual number. So instead, change that bit to:

          for (int i = 0; i < row; i++) {
              line = myFile.readLine();
              myTokens = new StringTokenizer(line, ",");
              for (int j = 0; j < col; j++) {
                 twodimarr[i][j] = Integer.parseInt(myTokens.nextToken());
              }
          }
    

    In addition, it's not good practice to store local variables as static class variables. Instead of doing public static TextFileInput myFile; at the beginning of the class definition, do TextFileInput myFile = new TextFileInput("twodimension8.txt"); at the top of main. (same for the other variables).