Validate if a String contains only numbers
Often it is necessary to validate input data. One such validation could be to check if a user has entered a sequence of numbers. This example shows how you can check a String to see if it only contains integers. This validation could be done with less code if we were using regular expressions, but this example aims to keep it simple and more understandable so we use the Character wrapper class instead. The Character class has a static method called isDigit() which takes a char value as argument and returns true if it's a number, or else it returns false. So we loop through the String and pass every character in it to the isDigit() method. If we find a non-digit character, we just halt the loop and return false. |
/** * * @author javadb.com */ public class Main { /** * This method checks if a String contains only numbers */ public boolean containsOnlyNumbers(String str) { //It can't contain only numbers if it's null or empty... if (str == null || str.length() == 0) return false; for (int i = 0; i < str.length(); i++) { //If we find a non-digit character we return false. if (!Character.isDigit(str.charAt(i))) return false; } return true; } /** * @param args the command line arguments */ public static void main(String[] args) { Main main = new Main(); System.out.println(main.containsOnlyNumbers("123456")); System.out.println(main.containsOnlyNumbers("123abc456")); } } |
The output from the example will be: true false See also: Validate if string is a number |
Search for code examples on this site
