0

I am pretty new to Java and have been trying to write some code so it will check the input received is only letters so no special characters or numbers can be put in.

So far I have gotten this far

    System.out.println("Please enter your first name");
    while (!scanner.hasNext("a-z")
    {
    System.out.println("This is not in letters only");
    scanner.nextLine();
    }
    String firstname = scanner.nextLine();
       int a = firstname.charAt(0);

This is clearly not working as it is just defining the input can only contain the characters a-z, I was hoping for a way to tell it it can only contain letters but have not been able to figure out yet how to.

Any help would be appreciated even a link to where I can read the proper commands and figure it out by myself :)

Thanks

Chris
  • 131
  • 2
  • 8

3 Answers3

1

You can use any of the below two methods:

public boolean isAlpha(String name) {
    char[] chars = name.toCharArray();

    for (char c : chars) {
        if(!Character.isLetter(c)) {
            return false;
        }
    }

    return true;
}

public boolean isAlpha(String name) {
    return name.matches("[a-zA-Z]+");
}
Community
  • 1
  • 1
Trying
  • 14,004
  • 9
  • 70
  • 110
0

You can use a simple regex for that

System.out.println("Please enter your first name");
String firstname = scanner.nextLine(); // Read the first name 
while (!firstname.matches("[a-zA-Z]+")) { // Check if it has anything other than alphabets
    System.out.println("This is not in letters only");
    firstname = scanner.nextLine(); // if not, ask the user to enter new first name
}
int a = firstname.charAt(0); // once done, use this as you wish
Rahul
  • 44,383
  • 11
  • 84
  • 103
  • 1
    Thank you so much :) at the moment it feels like I am trying to express myself in a new language, I know what I want to say but can't find the words :) – Chris Oct 20 '13 at 16:22
0
while (scanner.hasNext()) {
    String word = scanner.next();
    for (int i = 0; i < word.length; i++) {
        if (!Character.isLetter(word.charAt(i))) {
            // do something
        }
    }
}
Paul Samsotha
  • 205,037
  • 37
  • 486
  • 720