Why does Integer.parseInt produce Exception in thread "main" java.lang.NumberFormatException: For input string: ""

58 views Asked by At

Why does Integer.parseInt produce this error?

public static void main(String[] args) {
    String input = "6";
    Pattern pattern = Pattern.compile("[0-9]*");
    Matcher matcher = pattern.matcher(input);
    while (matcher.find()) {
        String str = matcher.group();
        System.out.println(Integer.parseInt(str));
    }
}

Exception in thread "main" java.lang.NumberFormatException: For input string: "" at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:67) at java.base/java.lang.Integer.parseInt(Integer.java:675) at java.base/java.lang.Integer.parseInt(Integer.java:781)

1

There are 1 answers

0
Rob Spoor On

Because your pattern uses *, after your single digit there is another match - an empty string. Use + instead, and that empty string won't match.