How do I check if a character representing a number?

Category: java.lang, viewed: 8490 time(s).

For validation purposes we might need to check if the data entered by our user is a valid data for our application. A simple mechanism for checking if a character inputted is a number or not can be done by using Character's class isDigit(char c) method. An example is shown below:

package org.kodejava.example.lang;

public class CharacterIsDigit
{
    public static void main(String[] args)
    {
        String numbers = "1234567890";
        for (int i = 0; i < numbers.length(); i++)
        {
            if (Character.isDigit(numbers.charAt(i)))
            {
                System.out.println(numbers.charAt(i)
                        + " is a number.");
            }
            else
            {
                System.out.println(numbers.charAt(i)
                        + " not a number.");
            }
        }
    }
}


Java Training

Sponsored Links