Search code examples
javastringconsolejava.util.scanneruser-input

How do I check for special characters in a String[Java]?


I am creating a console game.. and I want the players to be able to choose their own usernames. Having usernames like .-|\12b-}| can be really weird. I want to be able to check if the username has "special characters" in it. If the player has a special character in his/her username, I want the system to print out a message(something like: Please change your username). I don't want the code to just replace the letters.

Here is an example(follow this if you have an answer):

import java.util.Scanner; 
class StackOverflowExample {
  public static void main(String[] args) {
    System.out.println("Welcome New Player! What will your name be?");
    Scanner userInteraction = new Scanner(System.in);
    String userInput = userInteraction.nextLine();
    System.out.println("Welcome " + userInput + "!");
  }
}

Output:

You can see why this would be a problem

You can see why this would be super weird..

I want to be able to scan:

String userInput = userInteraction.nextLine();

for any weird characters. How would I go about scanning the String?


Solution

  • Try this. It continues to prompt for a username if anything other than letters are provided. Usernames like Battle101 or ~Hello~ are not allowed.

    Scanner userInteraction = new Scanner(System.in);
    String userInput = "";
    while (true) {
        System.out.println("Welcome New Player! What will your name be?");
        userInput = userInteraction.nextLine();
        if (userInput.matches("[a-zA-Z]+")) { // check that the input only contains letters
           // okay so exit loop
            break;
        }
        // else explain the problem and reprompt.
        System.out.println("Only alphabetic characters are permitted.\nPlease try again.");
    }
    System.out.println("Welcome " + userInput + "!");