0

I'm trying to extract one int from my txt that only contains one number but I'm getting the error: Exception in thread "main" java.lang.NumberFormatException: For input string: "3"

I've tried to just use .nextInt to directly extract the int from the txt file but that has n0ot worked so instead, I'm trying to extract the number from the txt file as a String and then converting it into an int within my code.

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

class Scratch {
    public static void main(String[] args) throws Exception{
        Scanner highScoreScan = new Scanner(new File("wordgamehighscores.txt"));//This file just has one integer which is the highscore.

        while (highScoreScan.hasNext()) {
    String highScoreInt = highScoreScan.next();
            int highScore= Integer.parseInt(highScoreInt);
    System.out.println(highScore);
}
    }
}

And here is the full error:

Exception in thread "main" java.lang.NumberFormatException: For input string: "3"
    at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
    at java.base/java.lang.Integer.parseInt(Integer.java:638)
    at java.base/java.lang.Integer.parseInt(Integer.java:770)
    at Scratch.main(scratch.java:10)
  • 2
    Use a debugger and check the string value doesn't contain unprintable chars – jhamon Apr 16 '19 at 15:28
  • You probably have invisible whitespace before or after the `3`, hence the confusing error message (might not even be visible while debugging). See [here](http://www.fileformat.info/info/unicode/char/200b/index.htm) for instance. You can just try and trim the `String` first like Hien Nguyen says. – Mena Apr 16 '19 at 15:33
  • @Mena yeah, I didn't realize that there can be invisible characters and stuff. I just tried using .trim() and it worked. Thanks for your help! – Tpixelminer Apr 16 '19 at 15:36

1 Answers1

1

You should trim space before parseInt

String highScoreInt = highScoreScan.next();
highScoreInt = highScoreInt.trim();
int highScore= Integer.parseInt(highScoreInt);
Hien Nguyen
  • 24,551
  • 7
  • 52
  • 62