JavaNube JavaNube - 1 year ago 77
Java Question

Java - validating a subject Code

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


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
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");

Answer Source

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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download