Why does Integer.parseInt throw a NumberFormatException on input that seems valid?

I am doing a simple exercise from a book, and I'm a little confused about how parseInt java function works. I read a line from the input file, used a StringTokenizer to split it, and now I want to parse each part as an integer.

I checked in the viewer that the input of the parseInt function is really a string that seems like a real integer (for example, "35"). However, when I try to use a function str.charAtfor my variable strwhile holding the value "35", I get strange results:

str.charAt(0) == ""
str.charAt(1) == "3"
str.charAt(2) == ""
str.charAt(3) == "5"

This is probably an encoding issue, so I tried to fix it using this method of reading a file:

InputStreamReader reader = new InputStreamReader(new FileInputStream(inputfile), "UTF-8");

(I explicitly saved the file using UTF-8 encoding in my editor), but this did not help. Any ideas what could be the problem and how to fix it?

EDIT: My sample

        InputStreamReader reader = new InputStreamReader(new FileInputStream(inputfile), "UTF-8");
        BufferedReader bfreader = new BufferedReader(reader);

        line = bfreader.readLine();
        while (line !=null)
        {
                String[] valueStrings = line.split(" ");
                String hole = valueStrings[0]; 

                int[] values = new int[4];
                for (int i = 0; i <values.length; i++){

                    String nr = valueStrings[i+1].trim(); 
                    values [i] = Integer.parseInt(nr);
                }

                // it breaks at the parseInt here, the rest is not even executed...

         }
+3
source share
1 answer

I assume this is actually:

str.charAt(0) == '\0'
str.charAt(1) == '3'
str.charAt(2) == '\0'
str.charAt(3) == '5'

It looks like it was most likely saved in UTF-16 rather than UTF-8, but if your text editor decided that it was designed to store the characters "zero", that makes sense. Try looking at the text file in a binary hex editor - I suspect you will find that every other byte is 0.

If this does not help, send a short but complete program that demonstrates the problem - so far we have seen only one line of your code.

+11

Source: https://habr.com/ru/post/1732601/


All Articles