We would like to know how to check if a character is a Letter or digit.
isDigit(): true if the argument is a digit (0 to 9), and false otherwise.
public class MainClass { public static void main(String[] args) { char symbol = 'A'; /*w w w . j a v a 2s . co m*/ if (Character.isDigit(symbol)) { System.out.println("true"); }else{ System.out.println("false"); } } }
Validate if a String contains only numbers
public class Main { public static boolean containsOnlyNumbers(String str) { for (int i = 0; i < str.length(); i++) { if (!Character.isDigit(str.charAt(i))) return false; }/*from ww w . j av a 2 s.com*/ return true; } public static void main(String[] args) { System.out.println(containsOnlyNumbers("123456")); System.out.println(containsOnlyNumbers("123abc456")); } }
The code above generates the following result.
isLetterOrDigit(): true if the argument is a letter or a digit, and false otherwise.
public class MainClass { public static void main(String[] args) { char symbol = 'A'; /*from w w w.j a v a 2 s. com*/ if (Character.isLetterOrDigit(symbol)) { System.out.println("true"); }else{ System.out.println("false"); } } }