Converting aplhanumeric string to numbers - NumberFormatException

I need to get the number 23 from the string "a23". When running the program below, the following error appears.

public class GetIntFromString {

    public static void main(String[] args) {

        String str = "a23";

        int i = Integer.parseInt(str);

        System.out.println("Integer value= "+i);

        System.out.println("value= "+str);

    }
}

      

Here is the stack trace

Exception in thread "main" java.lang.NumberFormatException: For Input String: "a23"

at java.lang.NumberFormatException.forInputString<NumberFormatException.java.48>
at java.lang.Integer.ParseInt<Integer.java.449>
at java.lang.Integer.ParseInt<Integer.java.499>
at GetIntFromString.main<GetIntFromString.java.9>

      

+3


source to share


5 answers


Just remove any unsigned characters;)



System.out.println("Integer value= "+str.replaceAll("[^0-9]","")); 

      

+4


source


The parseXXX () methods do not accept strings that do not match the requested type - an integer in this case. You will need to find a technique to determine the actual numeric part manually (or perhaps using a regular expression).



+2


source


If your prefix letter will always be only one character then try this

int i = Integer.parseInt(str.substring(1));

      

Otherwise, you need to find the digital part before calling parseInt

+2


source


You have to call replaceAll on str to remove every non-digit character. Parseint only accepts pure numeric strings.

+1


source


the parsing method only accepts numbers in string format. Otherwise, it will throw a NumberFormatException.

0


source







All Articles