Search code examples
javastringjoptionpane

How do I make a program that takes a string but disallows numbers?


I'm developing a game and it asks for a username at the start which will then be added to a txt file and saved. But the problem is that the user can write absolutely anything. Their usernames are infinite and can contain special characters and numbers which I do not want. And I have no idea how to stop it. I am writing in Java

The code I use to ask for a username is

player = new Player(level, 0, 0, input, JOptionPane.showInputDialog(this, "Please enter a username"));

And in the constructor for player it is simply

public Player(Level level, x, y, InputHandler input, String username)

Solution

  • I would keep prompting the user to enter valid information until they do.

    String username = null;
    do {
        username = JOptionPane.showInputDialog(null, "Please enter a username");
        // check if the username is invalid
        if(username.length() > 12 || username.length() < 4 || !username.matches("[a-zA-Z0-9]+")) {
            // show the user why they cant enter that username
            JOptionPane.showMessageDialog(null, "Username must be:\nbetween 4 and 12 characters characters\nonly letters and numbers", "Invalid Username", JOptionPane.INFORMATION_MESSAGE);
            // do the loop again
            username = null; 
        }
    } while(username == null);
    // at this point in the execution we can say that the username String is a valid username