ALx ALx
ALx ALx

Reputation: 111

Java check String input

I am trying to check an input String: - length - type - special char at the end

The input is a identity card like this 24659213Q.

So what I got for now is:

    public void datosUsuario() {
    System.out.print("Write ID: ");
    input = scanner.nextLine();
}


//ID check
public void comprobacion() {
    System.out.println("Checking ID length...");
    if (input.length() == 9){
        status = true;
        System.out.println("Length: OK!");
    } else {
        System.out.println("Length not OK! Try again!\n");
        status = false;
    }
}

So I am checking the entire String for having 8+1 length and now I am having problems checking if it has 8 digits and a char at the end of the input.

Any ideas would be apreciated! Thank you!

Upvotes: 0

Views: 478

Answers (5)

Shweta Gulati
Shweta Gulati

Reputation: 606

The method of regular expression can also be followed as mentioned above. There is one more way to do it.

1)Split the string into two -one with 8 characters and the other with last one character.

2)Parse the first String Integer.parseInt(subStringOfFirst8Char) in a try catch block catching NUmberFormatException.

If you don't catch the exception it is alright else it is wrong.

Upvotes: 0

JTeam
JTeam

Reputation: 1505

You can use reg ex,

  public static void comprobacion(String input) {
    status = false;
    if(input.matches("\\d{8}\\w{1}"))
    {
      status = true;
    }

  }

Here, \d{8} = eight digits \w{1} = one alphabetical character

Upvotes: 1

Donald Taylor
Donald Taylor

Reputation: 62

You could use "Character.isDigit()" to determine if a character is a digit or not. In other words, you could create a for loop to interate through each character, checking whether it is a digit or not. Here's an example:

String input = "24659213Q";
for(int c = 0; c < input.length()-1; c++){
    //Checks all but the last character
    if( !Character.isDigit( input.charAt(c) ) ){
        System.out.println("The String does not start with 8 digits");
    }
}
if( Character.isDigit( input.charAt(8) ) ){
    //Checks only last character
    System.out.println("The String does not end with a char");
}

Upvotes: 0

baltzar
baltzar

Reputation: 476

A simple method would be:

//ID check
public void comprobacion() {
System.out.println("Checking ID length...");
if (input.length() == 9) {
    if (Character.isAlphabetic(input.charAt(8)) {
        status = true;
        System.out.println("OK!");
    } else {
        status = false;
        System.out.println("Length: OK, but last character must be alphabetic");
    }
} else {
    System.out.println("Length not OK! Try again!\n");
    status = false;
}

Upvotes: 1

Moose Morals
Moose Morals

Reputation: 1648

I'd use a regular expression:

String input = scanner.nextLine();
input.matches("/^[0-9]{8}[A-Za-z]$/);

See String.matches and regular expression documentation.

Upvotes: 3

Related Questions