简体   繁体   中英

Java character input validation

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?

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

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

AP 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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM