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<>
at java.lang.Integer.ParseInt<>
at java.lang.Integer.ParseInt<>
at GetIntFromString.main<>



source to share

5 answers

Just remove any unsigned characters;)

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




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).



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



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



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



All Articles