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
Step: 1
The error you are encountering is due to the fact that when you split the row by space using inputne...Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started