PaulK
PaulK

Reputation: 17

Validating string format(pattern) input

Im trying to figure out how to validate the users input.I want the user to input something like a1 or B6.The input should be in the following pattern. letter from a to h followed by a number from 1 to 8, [String-number].Also the letter should be accepted either if it is capital either not.Here is my code.Any help is very much appreciated!

private void getUserInput() {
    Scanner scan = new Scanner(System.in);

    userGuess1 = scan.nextLine();
   // Here i should validate if the input is in the right format
    userGuess = userGuess1;

Upvotes: 1

Views: 4887

Answers (2)

DomantasJ1
DomantasJ1

Reputation: 133

You can split the input into an array of characters first. You can now check the length of their input using charArray.length . After this you can check if the two characters in the array are between your required characters by using if and else statements and < and > comparisons here is a simple example: (the Character.toLowerCase(char) means that it doesnt matter if the user enters the letter uppercase or lowercase)

    Scanner scan = new Scanner(System.in);
    String input = scan.next();
    char[] charArray = input.toCharArray();

    boolean validated = true;

    if(charArray.length != 2){
        validated = false;
    }

    if(charArray[1] > '8' || charArray[1] < '1'){
        validated = false;
    }

    if(Character.toLowerCase(charArray[0]) > 'h' || Character.toLowerCase(charArray[0]) < 'a'){
        validated = false;
    }

Upvotes: 0

ug_
ug_

Reputation: 11440

You can use the String method matches(String regex) method.

userGuess1 = scan.nextLine();
if(userGuess1.matches("[a-hA-H][1-8]")) {
    // valid
} else {
    // invalid
}

this results in the following:

A1 - valid
H9 - invalid
a2 - valid
h3 - valid

i8 - invalid 
zk - invalid


Regular expression breakdown!

  • Things inbetween brackets define a group of things, combined with the - dash you can define a range.
  • [a-hA-H] matches upper or lower case letters a through h
  • [1-8] matches a number that is 1 <= number <= 8

Upvotes: 2

Related Questions