John Doe
John Doe

Reputation: 2924

How to fix this exception in Java?

My code is like this

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

  public class ReadFile{
    public static void main(String[] args)throws Exception {
       Scanner scan = new Scanner(new File("input.txt"));
       int[][] arr = new int[4][4];

       for(int t = 1; t <= 2; t++){
        int firstRow = scan.nextInt();
        System.out.println(firstRow);
        for(int i = 0; i <= 4; i++){
         if(scan.hasNextLine()){
             String[] splited = scan.nextLine().split("\\s");
             for(String f : splited)
                System.out.println(f);
               for(int g = 0; g <= 4; g++){
                 arr[i][g] = Integer.parseInt(splited[i]); // at this point the exception is being thrown
              }
            }
          }

        }
      }

Through which I am trying to read a file having data arranged in following format

 2
 1 2 3 4
 5 6 7 8
 9 10 11 12
 13 14 15 16
 3
 1 2 5 4
 3 11 6 15
 9 10 7 12
 13 14 8 16

Basically I want to read the first number 2 (single value in a line) and 3(again a single value in line 6th from top) and store them in firstRowNum variable and secondNumRow variable and the rest of the numbers in two 4X4 matrices. But when I am running the code I am getting the following exception

  Exception in thread "main" java.lang.NumberFormatException: For input string: ""
 at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
 at java.lang.Integer.parseInt(Integer.java:504)
 at java.lang.Integer.parseInt(Integer.java:527)
 at ReadFile.main(ReadFile.java:20)

I think I am not setting the loops correctly.

Thanks

Upvotes: 0

Views: 243

Answers (2)

Marko Topolnik
Marko Topolnik

Reputation: 200296

Replace

splited[i]

with

f

as the argument to Integer.parseInt(). Also, don't use another loop for the g index; use

arr[i][g++]

and initialize g to 0 before the inner for each loop. Alternatively, use the g-based loop as it is, but replace splited[i] with splited[g].

You have other issues as well, such as using

i <= 4

as the upper bound condition of the loop, but your array's indices range from 0 to 3 (i < 4 should be used).

Upvotes: 3

jeojavi
jeojavi

Reputation: 886

You can check if the String is empty before the conversion to Integer, using the function String.isEmpty()

Upvotes: 1

Related Questions