Search code examples
javaswingnumberspattern-matchingjoptionpane

Java, make sure that a user doesn't enter numbers in a string


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?


Solution

  • You can use a simpler check:

    if (!name.replaceAll("[0-9]", "").equals(name)) {
        // name contains digits
    }
    

    The replaceAll call removes all digits from the name. The equals check would succeed only when there are no digits to remove.

    Note that throwing NumberFormatException in this case would be misleading, because the exception has a very different meaning.