Search code examples
javanumberformatexception

java.lang.NumberFormatException while reading from a file


I'm trying to create a basic program, it reads a file of unknown number of numbers arranged in a matrix, creates a list of arrays in String format to read it and then parses that to int for multiple other processes. I'm getting a java.lang.NumberFormatException when parsing, I know its probably because of a blank value getting parsed to an int. I have looked at other questions but can't seem to get it fixed. Here's part of the code:

public static void main(String[] args) {
    try {
            br = new BufferedReader(new FileReader(theFile));
            String line = null;

            while ((line = br.readLine()) != null) {                
                String[] aLine = line.split("/t");
                br.readLine();
                numLine.add(aLine);
            }
        } catch (IOException e){
        } finally {
            try {
                br.close();
            } catch (Exception e) {
            }
        }

    for (int i=0; i < numLine.size(); i++){
        for (int j = 0; j < numLine.get(i).length; j++){
            System.out.print(numLine.get(i)[j] + " ");
            //  if (!((numLine.get(i)[j]).equals("\t"))){
            intList.add(Integer.parseInt(numLine.get(i)[j]));
            //  }
        }
        System.out.println();
    }
}

And here is what the error says:

Exception in thread "main" java.lang.NumberFormatException: For input string: "6    10  9   10  12  "
    at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
    at java.lang.Integer.parseInt(Integer.java:580)
    at java.lang.Integer.parseInt(Integer.java:615)
    at readingTextFiles.Main.main(Main.java:34)

Please take into account I'm a newbie programmer, got all this from research, so I'm not really sure how the theory works.


Solution

  • Change the delimiter as @kayKay mentioned, You are trying to read the line again. I think you shouldn't ??

    public static void main(String[] args) {
    try {
        br = new BufferedReader(new FileReader(theFile));
        String line = null;
    
        while ((line = br.readLine()) != null) {
            String[] aLine = line.split("\t"); // Also as kaykay mentioned change /t to \t
            //br.readLine();  // You are reading the line again - Comment it out 
            numLine.add(aLine);
        }
    } catch (IOException e){
    } finally {
        try {
            br.close();
        } catch (Exception e) {
        }
    }
    
    for (int i=0; i < numLine.size(); i++){
        for (int j = 0; j < numLine.get(i).length; j++){
            System.out.print(numLine.get(i)[j] + " ");
            //  if (!((numLine.get(i)[j]).equals("\t"))){
            intList.add(Integer.parseInt(numLine.get(i)[j]));
        }
    System.out.println();
    }