Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why an actual number string read from a text can't be parsed with method Integer.valueOf() in java?

Tags:

java

parsing

Why an actual number string read from a text can't be parsed with method Integer.valueOf() in java?

Exception :

Exception in thread "main" java.lang.NumberFormatException: For input string: "11127"
    at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
    at java.lang.Integer.parseInt(Integer.java:580)
    at java.lang.Integer.valueOf(Integer.java:766)
    at sharingBike.ReadTxt.readRecord(ReadTxt.java:91)
    at sharingBike.ReadTxt.main(ReadTxt.java:17)

This is my code

        File fileView = new File(filePath);

        BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(fileView), "UTF-8"));

        String line;

        int count = 0;
        while ((line = in.readLine()) != null) {
            String[] lins = line.split(";");

            int value;
            value = Integer.valueOf(lins[0]);}
like image 862
林文烨 Avatar asked Nov 08 '17 13:11

林文烨


People also ask

How do you check if a string can be converted to int?

isdigit() method to check if a string can be converted to an integer, e.g. if my_str. isdigit(): . If the str. isdigit method returns True , then all of the characters in the string are digits and it can be converted to an integer.

What happens if integer parseInt fails?

We have used the parseInt method of the Integer class before. The method throws a NumberFormatException if the string it has been given cannot be parsed into an integer. The above program throws an error if the user input is not a valid number. The exception will cause the program execution to stop.

Is a string an integer Java?

For integer number Integer class provides a static method parseInt() which will throw NumberFormatException if the String does not contain a parsable int. We will catch this exception using catch block and thus confirm that given string is not a valid integer number. Below is the java program to demonstrate the same.


1 Answers

Here is the content of your string:

System.out.println(Arrays.toString("11127".getBytes()));

which outputs:

[-17, -69, -65, 49, 49, 49, 50, 55]

The first three bytes are a UTF-8 BOM.

You can fix it by removing non-digits from the string first (and use parseInt to return an int instead of an Integer):

int value = Integer.parseInt(lins[0].replaceAll("\\D", "");
like image 63
assylias Avatar answered Nov 14 '22 23:11

assylias