Reputation: 332
I have found how to validate that an input is a number using try/catch but how do I go about validating that a user input is alphabetical only and contains no numbers?
Upvotes: 1
Views: 15717
Reputation: 44808
public static boolean containsNumbers(String str){
for(char ch : str.toCharArray()){
if(Character.isDigit(ch)){
return true;
}
}
return false;
}
Upvotes: 2
Reputation: 500663
You could use a simple regular expression:
if (str.matches("[a-zA-Z]+$")) {
// str consists entirely of letters
}
Note that this only works with letters A-Z
and a-z
. If you need to properly support Unicode, a better method is to loop over the characters of the string and use Character.isLetter()
.
Upvotes: 3
Reputation: 9070
One way is to use regular expressions.
private static Pattern p = Pattern.compile("^[A-Za-z]+$");
public static boolean match(String s) {
return p.matcher(s).matches();
}
One other way can be iterate through all characters in your string and check if they are alphabetical or not.
Upvotes: 1