2

I want to validate a single character in a java application. I don't want the user to be able to enter a character outside the range [a - p] (ignoring uppercase or lowercase) or numbers.

Scanner input = new Scanner(System.in);

System.out.print("Choose letter in range [a - p]");
letter = input.next().charAt(0);

Any ideas?

1
  • Improved question grammar. Commented Apr 23, 2015 at 3:40

3 Answers 3

3

you can use regex to filter input

.matches("^[a-pA-P0-9]*$") //this will not allow outside range of [a-p A-P] or numbers

^ Assert position at start of the string

- Create a character range with the adjascent tokens

a-p A single character in the range between a and p (case sensitive)

A-P A single character in the range between A and P (case sensitive)

0-9 A single character in the range between 0 and 9

* Repeat previous token zero to infinite times, as many times as possible

$ Assert position at end of the string

like this:

    Scanner input = new Scanner(System.in);

    System.out.print("Choose letter in range [a - p]");
    letter = input.next().charAt(0);

    if (Character.toString(letter).matches("^[a-pA-P0-9]*$")) {
         System.out.println("valid input");
    }else{
         System.out.println("invalid input");
    }

SEE REGEX DEMO

Sign up to request clarification or add additional context in comments.

Comments

0

you can encapsulate it with a while loop to check if the letter is in the range or not and just keep asking the user to input a letter

do {
    System.out.print("Choose letter in range [a - p]"); letter = input.next().charAt(0);
} while (letter is not in range of [a-p]); // pseudo code

Comments

0

If you're not familiar with regex, simple checks on the input can take care of it.

        System.out.print("Choose letter in range [a - p]");
        String letter = input.nextLine();
        if (letter.length() == 1 && ('a' <= letter.charAt(0) && letter.charAt(0) <= 'p')) {
            System.out.println(letter);
        } else {
            System.out.println("Invalid input");
        }

I'm using nextLine() in the event that multiple characters are accidentally entered, which is why I check that the length of letter == 1 and that the letter falls in the range that I want, otherwise it is invalid input.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.