简体   繁体   中英

Invalid int when converting from string to integer

I'm trying to convert a string that contains just numbers to integer using int number = Integer.parseInt(string) , but it returns #

error: Invalid int: "number"

For example, if the string is "10", it returns: Invalid int: "10" . What is wrong?

Edit:

FileInputStream fis;
        int number =0;
        String line="";
        try
        {
            fis = new FileInputStream(getFilesDir()+pathToFile);
            BufferedReader reader = new BufferedReader(new InputStreamReader(fis));
            line=reader.readLine();
            Log.e("Read Line", "Read line: *" +line+ "*"); //returns *10*
            try
            {
                number = Integer.parseInt(line.trim());
            }
            catch(NumberFormatException nfe)
            {
                Log.e("ERROR CONVERTING", nfe.getMessage()); // return above error
            }
            reader.close();

        }
        catch(Exception ex)
        {
            Log.e("ERROR OPENING FILE", "Can't open file: "+ex.getMessage());
        }

I used the code in the answer from this question: LINK

str = str.replaceAll("\\D+","");

Don't know why it doesn't work without this, because there are no other characters besides numbers in the string, but not it works.

Some times it means "the number is too big".

I come across a situation where it happens because my number was too big. Example:

Integer.parseInt("201506121234567");

It causes me the exception NumberFormat.

To solve, I changed to this:

Long.parseLong("201506121234567");

Hope it helps someone!

Did you actually try with "10" or any other number? The error is pretty specific.

Invalid int: "number"

This means that in this line

Integer.parseInt(string)

string has the value "number" . Check where are you setting this value and verify that you're actually setting a numeric string.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM