Home >Java >javaTutorial >How to Prevent `java.lang.NumberFormatException` When Parsing Non-Integer Strings in Java?

How to Prevent `java.lang.NumberFormatException` When Parsing Non-Integer Strings in Java?

Susan Sarandon
Susan SarandonOriginal
2024-12-08 14:17:11217browse

How to Prevent `java.lang.NumberFormatException` When Parsing Non-Integer Strings in Java?

Preventing java.lang.NumberFormatException for Non-Integer String Input

While encountering a java.lang.NumberFormatException with the message "For input string: "N/A"", it indicates that you are attempting to parse a string that does not represent a valid integer into an integer value. The string "N/A" in this case is not an integer.

Solution:

There are two approaches to prevent this exception:

Exception Handling:

Use try-catch block to handle the NumberFormatException and take appropriate action in case of a non-integer string:

try {
    int i = Integer.parseInt(input);
} catch (NumberFormatException ex) {
    // Handle the exception here, e.g., print an error message or replace the non-integer value with a default value.
}

Integer Pattern Matching:

Validate the input string using a regular expression before parsing it to an integer:

String pattern = "-?\d+";
if (input.matches(pattern)) { // Checks if the string matches the pattern of an integer (including negative values)
    int i = Integer.parseInt(input);
} else {
    // The input string is not an integer. Handle it appropriately.
}

By implementing either of these approaches, you can ensure that only valid integer strings are parsed into integers, preventing the occurrence of the java.lang.NumberFormatException.

The above is the detailed content of How to Prevent `java.lang.NumberFormatException` When Parsing Non-Integer Strings in Java?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn