0

for the last few hours i've been trying to get this code to only allow character input, as its for accepting names.. I have been following the same type of method i used to allow only integers, but with no luck. any advice would be great, Here is my code

            String name;
            System.out.println("Enter student's name: ");
            name = in.nextLine();
            while (!in.nextLine().matches("[a-zA-Z]"));
            {   
                System.out.println("Please enter a valid name!: ");
                in.next();
                }
            name = in.nextLine();
user3050340
  • 359
  • 2
  • 5
  • 12

4 Answers4

2

Your regex checks if the line matches exactly one [a-zA-Z] character. You probably want to check at least one: [a-zA-Z]+

Bear in mind that the way you are checking, you won't get what you have checked in the variable name, as you are consuming it in your checking. Can I propose an alternative:

System.out.println("Enter student's name: ");
String name = in.nextLine();
while(!name.matches("[a-zA-Z]+")){
    System.out.println("Please enter a valid name!");
    name = in.nextLine();
}
Sinkingpoint
  • 7,449
  • 2
  • 29
  • 45
1

I'm not too familiar with regex, personally, so I would just go with a method that takes a string and determines whether it is only comprised of the alphabets.

[EDIT] Shame on me, the method for testing if a character is a letter is static. Thanks to dansalmo for reminding me.

public static boolean isAlphabetic(String s) {
    for(int i = 0; i < s.length(); i++) {
        if (!Character.isLetter(s.charAt(i))) return false;
    }
    return true;
}
dansalmo
  • 11,506
  • 5
  • 58
  • 53
Vineet Kosaraju
  • 5,572
  • 2
  • 19
  • 21
  • Use `if (!Character.isLetter(s.charAt(i))) return false`. Otherwise Static Error: No method in Character with name 'isLetter' matches this invocation. – dansalmo Dec 04 '13 at 02:10
0

Did you check the value of the variable name? While you assign the input to name , you seem to read the next line for regex check. Remove the in.next too and it should work fine

Suresh C Nair
  • 33
  • 1
  • 6
0

Similar to Bucco's solution but iterating over a char array:

public static boolean isAlphabetic(String s) {
    for(char c : s.toCharArray())
        if (!Character.isLetter(c)) return false;
    return true;
}
dansalmo
  • 11,506
  • 5
  • 58
  • 53