Dylan Kolson Dylan Kolson - 1 year ago 132
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"));

String line = scanner.nextLine();

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


1, The Shawshank Redemption ,9.2,1994
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 Source

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);


rank = rank.replaceAll("[^0-9]+", "")
int real_rank = Integer.parseInt(rank); //remove everything non-digit from your input, including \n symbols
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download