Dylan Kolson Dylan Kolson - 3 months ago 26
Java Question

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

So I am reading in a CSV file which works fine if everything is a string. But when i try and parse Integers out of the file it no longer will work.

Scanner scanner = new Scanner(new File("top250.csv"));
scanner.useDelimiter(",");

while(scanner.hasNextLine()){
String line = scanner.nextLine();
System.out.println(line);

String[] parts = line.split(",");
String rank = parts[0].trim();
System.out.println(rank);
int real_rank = Integer.parseInt(rank);
}


Output:

1, The Shawshank Redemption ,9.2,1994
1
Exception in thread "main" java.lang.NumberFormatException: For input string: "1"
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 movieranker.MovieRanker.createData(MovieRanker.java:45)
at movieranker.MovieRanker.main(MovieRanker.java:25)

Answer

java.lang.NumberFormatException indicates that the application has attempted to convert a string to one of the numeric types, but that the string does not have the appropriate format.

This exception occurs because in the case that only a number is inputed, the actual string produced may have some invisible charachters and not "1". Thus, the format is incorrect. A simple fix would be:

Line changed from:

int real_rank = Integer.parseInt(rank);

to:

rank = rank.replaceAll("[^0-9]+", "")
int real_rank = Integer.parseInt(rank); //remove everything non-digit from your input, including \n symbols