How to check if a string is numeric

ht‮spt‬://www.lautturi.com
How to check if a string is numeric

To check if a string is numeric in Java, you can use the isDigit method of the Character class to check if each character in the string is a digit.

Here's an example of how you might do this:

String str = "12345";

boolean isNumeric = true;
for (int i = 0; i < str.length(); i++) {
    if (!Character.isDigit(str.charAt(i))) {
        isNumeric = false;
        break;
    }
}

if (isNumeric) {
    System.out.println("The string is numeric.");
} else {
    System.out.println("The string is not numeric.");
}

In this example, the charAt method is used to get the character at a specific index in the string, and the isDigit method is used to check if the character is a digit. If any character is not a digit, the isNumeric variable is set to false and the loop is terminated.

After the loop, the isNumeric variable is checked, and the appropriate message is printed to the console.

Created Time:2017-11-01 12:04:59  Author:lautturi