wkg86
wkg86

Reputation: 33

NumberFormatException when converting String to Integer

I want to transform String array to Integer. I wrote this, but eclipse returns a error:

Here is the code:

public static void main(String[] args) throws IOException {
    BufferedReader br = new BufferedReader(new FileReader("array_list.csv"));
    String everything = "";
    try {
        StringBuilder sb = new StringBuilder();
        String line = br.readLine();

        while (line != null) {
            sb.append(line);
            sb.append('\n');
            line = br.readLine();
        }
        everything = sb.toString();
    } finally {
        br.close();
    }
    int firstArrLenght = everything.indexOf("]");
    int secondArrStartIndex = everything.lastIndexOf("[") + 1;
    int secondArrLenght = everything.lastIndexOf("]") - secondArrStartIndex;
    String[] firstStrArr = everything.substring(1, firstArrLenght).split(",");
    String[] secondStrArr = everything.substring(secondArrStartIndex, secondArrLenght).split(",");

And eclipse doesn't like these rows. I want to convert here String Array to Integer. Then I'll use the ints for the other logic.

    int[] firstArray = transformToInt(firstStrArr);
    int[] secondArray = transformToInt(secondStrArr);

}


private static int[] transformToInt(String[] arr) {
    int[] result = new int[arr.length];
    for(int i = 0; i < arr.length; i++) {
        result[i] = Integer.parseInt(arr[i].trim());
    }

    return result;
}

Exception stack trace:

Exception in thread "main" java.lang.NumberFormatException: 
For input string: "" at java.lang.NumberFormatException.forInputString(Unknown Source)
 at java.lang.Integer.parseInt(Unknown Source)
 at java.lang.Integer.parseInt(Unknown Source)
 at Java.transformToInt(Java.java:38)
 at Java.main(Java.java:30) 

Any ideas what is wrong?

Upvotes: 1

Views: 8423

Answers (1)

Suresh Atta
Suresh Atta

Reputation: 122026

 java.lang.NumberFormatException: For input string: ""   

So the current String here you are trying to parse is empty in the line

  result[i] = Integer.parseInt(arr[i].trim());

It's not possible to get an integer value from a empty string,That's what exception is saying.

What you can do is just check the emptiness of String before parsing it.

Upvotes: 5

Related Questions