NumberFormatException: For input string:"2,"

2020-02-06 java

I am new in Java and I am trying to read a file and read the contents of a file to 2d array, but I got:

Exception in thread "main" java.lang.NumberFormatException: For input string: "2,"

Here is my code

import java.io.*;
import java.util.LinkedList;
import java.util.List;
import java.util.Scanner;

public class File {

public static void main(String[] args) throws Exception {
    String s[] = {"hello the you", "23"};
    Scanner input = new Scanner(new BufferedReader(new FileReader("hello.txt")));
    int x = 10;
    int y = 10;
    int[][] desktop = new int[x][y];
    while (input.hasNextLine()){
        for (int i = 0; i <desktop.length ; i++) {
            String[] line = input.nextLine().trim().split(" ");
            for (int j = 0; j <line.length ; j++) {
                desktop[i][j] = Integer.parseInt(line[j]);
            }

        }
    }
    for (int i = 0; i <desktop.length ; i++) {
        for (int j = 0; j <desktop[i].length ; j++) {
            System.out.print(desktop[i][j] + " ");
        }
    }


}

}

My hello.txt file is

There should be a specific text at the top of each page

2, 2, 2, 2, 2, 2, 2, 2, 2, 2
2, 0, 0, 0, 0, 0, 0, 0, 0, 2
2, 0, 0, 0, 0, 0, 0, 0, 0, 2
2, 0, 0, 0, 0, 0, 0, 0, 0, 2
2, 0, 0, 1, 3, 4, 0, 0, 0, 2
2, 0, 0, 0, 3, 4, 0, 0, 0, 2
2, 0, 0, 0, 0, 0, 0, 0, 0, 2
2, 0, 0, 0, 0, 0, 0, 0, 0, 2
2, 0, 0, 0, 0, 0, 0, 0, 0, 2
2, 2, 2, 2, 2, 2, 2, 2, 2, 2

Output should store in 2d array.

Answers

Change input.nextLine().trim().split(" "); to input.nextLine().trim().split(", ");. That will remove the , that is causing you problems.

Either of the following will work:

String[] line = input.nextLine().split(",");
for (int j = 0; j < line.length; j++) {
    desktop[i][j] = Integer.parseInt(line[j].trim());
}

or

String[] line = input.nextLine().trim().split(", ");
for (int j = 0; j < line.length; j++) {
    desktop[i][j] = Integer.parseInt(line[j]);
}

[Update]

Your updated hello.txt has There should be a specific text at the top of each page and also a blank line after that. In order to skip these two lines, use the following piece of code before your while loop:

for (int i=0; i<2 && input.hasNextLine(); i++){
    input.nextLine();    
}

Related