Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - validating a subject Code

I have a subject code e.g: ABC123 that is a string

I need to ensure that it is of length 6, the first 3 characters are letters and the last 3 are numbers.

I would like to try and do it all in an if statement? I can work the length but cannot figure out the numeric and letter part of things. e.g:

public void isValidCode(String subjectCode2){
    str = subjectCode2;
    if (str.length() == 6 && """"NEED TO TEST OTHERS HERE??""" ) {
        System.out.println("The code is valid");
    }
    else {
        System.out.println("The code is not valid");
    }
like image 235
JavaNube Avatar asked Dec 13 '25 00:12

JavaNube


1 Answers

You can always use Regular Expressions, and the matches() method of the String class.

if (str.matches("[a-zA-Z]{3}[0-9]{3}")) {
    // Validation succeeded
}
else {
    // Validation failed
}
like image 90
Matias Cicero Avatar answered Dec 15 '25 12:12

Matias Cicero



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!