I’m trying to create a text based game in Java that I will ask for a user’s name and insert it into the game. I’m trying to evaluate with the string that they entered has any number. i.e 09452 or asdf1234.
Here is the code that is relative to the problem.
String name, choiceSelection;
int choice;
name = JOptionPane.showInputDialog(null, "Enter your name!");
//CHECKS IF USER ENTERED LETTERS ONLY
if (Pattern.matches("[0-9]+", name))
{
throw new NumberFormatException();
}
else if (Pattern.matches("[a-zA-Z]+", name))
{
if (Pattern.matches("[0-9]+", name))
{
throw new NumberFormatException();
}
}
I’m trying to figure out if any number is in the string and if so, throw a NumberFormatException so that they know they didn’t follow the correct prompt.
What is the best way to make sure the user doesn’t enter numbers in the name String?
You can use a simpler check:
The
replaceAllcall removes all digits from thename. Theequalscheck would succeed only when there are no digits to remove.Note that throwing
NumberFormatExceptionin this case would be misleading, because the exception has a very different meaning.