Question: I can't get my program to read the array file and print it. I've included the data.txt file, the program and the error code it's

I can't get my program to read the array file and print it.  I've included the data.txt file, the program and the error code it's giving me

 

data.txt:

1 2 3 4 5 6 7 8 9


Program:

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class TwoDimensionalArray {

  public static void main(String[] args) {
      // create 2 dimensional array
      int[][] twoDArray = new int[4][4];
      // Create scanner object
      try {
          Scanner input = new Scanner(new File("C:/Users/jahoo/Documents/data.txt"));
          // check data is available
          if (input.hasNextLine()) {
              // iterate each row
              for (int j = 0; j < twoDArray.length; j++) {
                  // split row by space " "
                  String[] rowArray = input.nextLine().split(" ");
                  // iterate array row
                  for (int i = 0; i < rowArray.length; i++) {
                      twoDArray[j][i] = Integer.parseInt(rowArray[i]);
                  }
              }

          }
      } catch (FileNotFoundException e) {
          e.printStackTrace();
      }

      // print array details
      // iterate each row by row
      for (int i = 0; i < twoDArray.length; i++) {
          // iterate column values
          for (int j = 0; j < twoDArray.length; j++) {
              System.out.print(twoDArray[i][j] + " ");
          }
          System.out.println();
      }

  }

}

 

error:
Exception in thread "main" java.lang.NumberFormatException: For input string: "1,"
at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:67)
at java.base/java.lang.Integer.parseInt(Integer.java:668)
at java.base/java.lang.Integer.parseInt(Integer.java:786)
at TwoDimensionalArray.main(TwoDimensionalArray.java:21)

 

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock

The error you are encountering is due to the fact that when you split the row by space using inputne... View full answer

blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Programming Questions!