Restrict user to input numbers

`Scanner scanner = new Scanner(System.in);
 System.out.println("Enter your name:");
 String userName = scanner.nextLine();
 if (scanner.hasNextDouble()){
 System.out.println("You can't enter numbers");
  }`

Here i can’t print “You can’t enter numbers”. Or is there any other option to restrict user to input numbers?

Answer

You can try out something like below

public static void main(String[] args) {
    boolean validUsername = false;
    String regexForNumbers = ".*\d.*";

    Scanner scanner = new Scanner(System.in);
    System.out.println("Enter your name:");
    while (!validUsername) {
        String userName = scanner.nextLine();
        if(userName.matches(regexForNumbers)){
            System.out.println("Username Can not contain numbers");
            System.out.println("Please Enter username again:");
        }else{
            validUsername = true;
        }
    }
 }

Here String regexForNumbers = ".*\d.*"; will check whether the username contains a number,and you can expect something like this,

Enter your name:
maneesha123
Username Can not contain numbers

Please Enter username again:
123
Username Can not contain numbers

Please Enter username again:
maneesha