Reputation: 127
If you make a variable type String you can still input numbers.
Example:
"Enter name: 123"
The name is still accepted. How would I make it so a variable name only accepts letters, otherwise an error message will appear?
Upvotes: 2
Views: 554
Reputation:
You could check to see whether the string is numeric using a lambda expression:
String myString = "abcdef1234567890";
if (myString.chars().allMatch( Character::isDigit ))
Will output True if the string only contains numbers
Upvotes: 0
Reputation: 1126
If using a JTextField or something that allows listeners instead of just the command line, you can prevent the user from inputting numbers with a KeyListener:
userEntry.addKeyListener(new KeyAdapter() {
@Override
public void keyTyped(KeyEvent e) {
if (Character.isDigit(e.getKeyChar())) {
e.consume();
}
}
});
Upvotes: 0
Reputation: 319
I don't know any native function to do this, buy you can simply read the string (char per char) and ask if the value is between 65 and 90 (capital letters) or 97 and 122 (normal letters).
The code would be:
String string = "ABCD";
boolean hasOtherCharacters = false;
for ( int i = 0; i < string.length();i++ )
{
if ( !(string.charAt(i) >= 65 && string.charAt(i) <= 90) && !(string.charAt(i) >= 97 && string.charAt(i) <= 122) )
{
hasOtherCharacters = true;
break;
}
}
if ( hasOtherCharacters )
{
//WHATEVER YOU WANT
WARNING: This solution applies if your character set is between those ASCCI range.
Upvotes: 1
Reputation: 5540
Without the help of any additional library you just use Javas pattern matcher:
Pattern p = Pattern.compile("\\D*");
String test1 = "abc";
String test2 = "abc123";
Matcher m1 = p.matcher(test1);
System.out.println("does test1 only contain letters? " + m1.matches());
//prints true
Matcher m2 = p.matcher(test2);
System.out.println("does test2 only contain letters? " + m2.matches());
//prints false
Upvotes: 1
Reputation: 1652
You cant necessarily limit the user input to just numbers, however you can validate that input to ensure that it meets your expectations. For example, if you want to ensure that your string does not contain any numbers you can do:
if(str.matches(".*\\d.*")){
// contains a number
} else{
// does not contain a number
}
Upvotes: 5