1

I need to only allow a user to enter a character from the a-z range. I was thinking of using an if statement but its not working out for me.

        System.out.println("Please enter letters of the alphabet");
        String input1 = scnObj.nextLine();
        if (input1 != a-z) {
        System.out.println("Please try again.");
        }  
        else 
        {
        System.out.println("Correct.");
        }

3 Answers3

0

You could use a regular expression, but a simpler solution might be to take advantage of the fact that the characters in a - z are a in a linear progression within the character set tables and do something like...

    String input1 = scnObj.nextLine();
    if (!input1.trim().isEmpty()) {
        char inputChar = input1.charAt(0);
        if (inputChar >= 'a' && inputChar <= 'z') {
            // Everything is good
        } else {
            // Everything is bad
        }
    }
MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
0

This sounds like the perfect time for a regex implementation. If you have never heard regex I recommend checking out this video. Essentially it is used to match patterns within a string. For java you could simply check whether each character is a lower case letter with:

System.out.println("Please enter letters of the alphabet");
String input1 = scnObj.nextLine();
if (!input1.matches("[a-z]*") {
    System.out.println("Please try again.");
}  else  {
    System.out.println("Correct.");
}

However it might have to add a little more if you want to allow for spaces/hyphens. Good luck!

nomore2step
  • 155
  • 1
  • 1
  • 8
0

You can use regexp. Your case is simple and something like this:

if(!Pattern.compile("[a-z]*").matcher(line).matches()){
   System.out.println("Please try again.");
}

If you want include also Uppercase, modfy if condition like this:

if(!Pattern.compile("[a-zA-Z]*").matcher(line).matches()){
   System.out.println("Please try again.");
}

If space are allowed:

if(!Pattern.compile("[a-zA-Z\\s]*").matcher(line).matches()){
   System.out.println("Please try again.");
}

In any case and for more complex cases please read the java doc

Renato
  • 2,077
  • 1
  • 11
  • 22