Search code examples
javafileline

How to assign a text file's lines of integers into 2D tables in Java?


I have the sample.txt which contains 100 Integers (range 0-9) in every line formatted like this:

9 2 0 3 4 1 0 7 5 3 7 8 6 2 0 1 4 4 5 9 0 3 2 1 7 (etc... 100 numbers)

I want to scan the file and put every line into a 10x10 table. So:

public void loadTableFromFile(String filepath){

    try (Scanner s = new Scanner(new BufferedReader(new FileReader(filepath)))) {

        String line;
        while (s.hasNextLine()) {

        // WHAT HERE? THIS BLOCK DOES NOT WORK
        /*    if (s.hasNextInt()) {
                //take int and put it in the table in the right position procedure
            } else {
                s.next();
            }  */
        // END OF NOT WORKING BLOCK

        }
    } catch (FileNotFoundException e){

    }

}

Solution

  • How about something like this?

    public void loadTableFromFile(String filepath) {
      Scanner s = null; // Our scanner.
      try {
        s = new Scanner(new BufferedReader(
            new FileReader(filepath))); // get it from the file.
        String line;
        while (s.hasNextLine()) { // while we have lines.
          line = s.nextLine(); // get a line.
          StringTokenizer st = new StringTokenizer(line, " ");
          int i = 0;
          while (st.hasMoreTokens()) {
            if (i != 0) {
              System.out.print(' '); // add a space between elements.
            }
            System.out.print(st.nextToken().trim()); // print the next element.
            i++;
            if (i % 10 == 0) { // Add a new line every ten elements.
              System.out.println();
            }
          }
          System.out.println(); // between lines.
        }
      } catch (FileNotFoundException e) {
        e.printStackTrace();
      } finally {
        if (s != null)
          s.close();
      }
    }