2

Getting the following error while reading the contents of the file, I think that my code is not converting the it into integer rightly following are the errors:

Exception in thread "main" java.lang.NumberFormatException: For input string: "3 "
    at java.lang.NumberFormatException.forInputString(Unknown Source)
    at java.lang.Integer.parseInt(Unknown Source)
    at java.lang.Integer.parseInt(Unknown Source)
    at Program.main(Program.java:192)

and here is the code:

    FileReader fin = new FileReader("task.txt");
    BufferedReader sr = new BufferedReader (fin);
    int count = 0;
    int number = Integer.parseInt(sr.readLine());
Ali Sajid
  • 3,964
  • 5
  • 18
  • 33
  • Just a word of advice since it looks like you might need to read multiple lines from this file. I would suggest reading all the lines at once into an `List`. See the second, very compact way of doing this provided in the top answer [here](http://stackoverflow.com/questions/326390/how-to-create-a-java-string-from-the-contents-of-a-file/326440#326440). – Will Byrne Apr 19 '15 at 18:11
  • Thanks @Will for your concern actually there was a space after 3 which I was neglecting. – Ali Sajid Apr 19 '15 at 18:40

1 Answers1

4

You are trying to parse a String that contains a space and a digit - "3 ".

You should eliminate the spaces before parsing to int :

 int number = Integer.parseInt(sr.readLine().trim());
Eran
  • 387,369
  • 54
  • 702
  • 768