Home > Java > javaTutorial > How Can I Prevent `java.lang.NumberFormatException` When Parsing 'N/A' and other Non-Integer Strings in Java?

How Can I Prevent `java.lang.NumberFormatException` When Parsing 'N/A' and other Non-Integer Strings in Java?

Susan Sarandon
Release: 2025-01-02 15:23:43
Original
180 people have browsed it

How Can I Prevent `java.lang.NumberFormatException` When Parsing

Preventing java.lang.NumberFormatException for Input String "N/A"

An error known as "java.lang.NumberFormatException" arises when attempting to interpret a non-integer string, such as "N/A," as an integer. To avoid this exception, several approaches can be taken.

1. Exception Handling:

An exception handler can be implemented to catch and handle the exception:

try {
    int i = Integer.parseInt(input);
} catch (NumberFormatException ex) { // handle the exception
    ...
}
Copy after login

2. Integer Pattern Matching:

Alternatively, using regular expressions, you can verify whether the input matches the pattern of an integer:

String input = ...;
String pattern = "-?\d+";
if (input.matches(pattern)) { // any positive or negative integer or not?
    ...
}
Copy after login

By employing either exception handling or integer pattern matching, you can prevent the exception from occurring when parsing input strings that are not integers.

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

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template