Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

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

Step: 1

The error you are encountering is due to the fact that when you split the row by space using inputne... blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image_2

Step: 3

blur-text-image_3

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Income Tax Fundamentals 2013

Authors: Gerald E. Whittenburg, Martha Altus Buller, Steven L Gill

31st Edition

1111972516, 978-1285586618, 1285586611, 978-1285613109, 978-1111972516

More Books

Students also viewed these Programming questions