0

I wrote a program to read username from keyboard. When I enter any integer or special characters, it is taking that values and displaying on console. But I want that it should not take any integers and special characters. It should take only letters and if any integer or special character is there, then it should give the error message and should not store that value. Can anybody help me with this problem?

The program program which I wrote is

import java.util.Scanner;

public class CheckIsEmpty {

   public static void main(String[] args) {

      Scanner sc = new Scanner(System.in);

        while (true) {
             System.out.println("Enter User Name:: ");
             System.out.println();
             String usn = sc.nextLine();

          if (usn.trim().isEmpty()) {
               System.out.println("Don't Give Space");
               System.out.println();
          }//if
          else if (usn.isEmpty()) {
               System.out.println("User Name Is Mandatory");
               System.out.println();
          } // if
          else {
               System.out.println("Hi " + usn);
               System.out.println("Welcome To Java");
               break;
          }// else

    }//while
}//main

}// class

Brandon Minnick
  • 13,342
  • 15
  • 65
  • 123
Abhishek Kumar
  • 332
  • 3
  • 15
  • 2
    Possible duplicate of [How to filter a Java String to get only alphabet characters?](https://stackoverflow.com/questions/30780074/how-to-filter-a-java-string-to-get-only-alphabet-characters) – Treyten Carey Feb 05 '18 at 16:13
  • After you get the sc.nextLine() into your string usn variable, check if the variable contains any integers or special characters, then display error if so. – Ryan Wilson Feb 05 '18 at 16:13

2 Answers2

0

You can use regex here. If all characters are letters then following code will return true.

usn.matches("[a-zA-Z]+")

If an input string is having any other char it will return false.

Hope it helps.

nagendra547
  • 5,672
  • 3
  • 29
  • 43
0

You can use pattern matching..

boolean b = Pattern.compile("[a-zA-Z]+").matcher(username).matches();