Skip to content
Advertisement

i am trying to take user input and display with a condition that it should be Alphabet

    public static void main(String[] args) {
        
    
    String name;
    System.out.println("Please Enter Name");
    Scanner s=new Scanner(System.in);
    //s.nextLine();
    name=s.nextLine();
    if(isAlpha(name)) {
        System.out.println("Name is: " +name);
    }else {
        System.out.println("please Enter valid name");
    }
    
    }
    
    public static boolean isAlpha(String name) {
        char[] charArray = name.toCharArray();
        for (int i = 0; i < charArray.length; i++) {
           char ch = charArray[i];
           if (!(ch >= 'a' && ch <= 'z')) {
              return false;
           }
           else if (!(ch >= 'A' && ch <= 'Z')) {
                  return false;
               }
           else {
               return true;
           }
        }
        return true;
        
    }

i am trying to take user input and display it only if it satisfy a condition that it should contain alphabets only but it shows every entry as invalid why?

Advertisement

Answer

Use this

public static boolean isAlpha(String s) {
        return s != null && s.matches("^[a-zA-Z]*$");
    }
Advertisement