Home > Software engineering >  Java check if a scan input is both a specific string and only three digits
Java check if a scan input is both a specific string and only three digits

Time:05-26

I have a project that is asking, "Order is entered by the user. The order either begins with FB or SB and then has three digits after those letters. Must check to be sure the order number is either letter code and only three digits." in java.

ex. Create order number [FB or SB for type of gift and three integers]: FB343

I'm struggling to find how to validate both in one input.

CodePudding user response:

That looks like a regular expression to me. You can use a Pattern and Matcher to test if the given order matches the Pattern; does it start with F or S then B and then three digits. Like,

String[] arr = { "SB123", "FB124", "CBXXX", "FB1234" };
Pattern p = Pattern.compile("[SF]B\\d{3}");
for (String s : arr) {
    Matcher m = p.matcher(s);
    System.out.printf("%s %b%n", s, m.matches());
}

Outputs

SB123 true
FB124 true
CBXXX false
FB1234 false

CodePudding user response:

Regex should do the trick.

Just run Pattern.matches() on the sequence ^((FB)|(SB){1})([0-9]{3})$

Something like

public class Matcher(string){
bool = Pattern.matches(^((FB)|(SB){1})([0-9]{3})$), string);
}

CodePudding user response:

So to further enhance the Order Number validation:

String orderNumber = "fb323"; // The Order Number.

int minNumber = 100;  // The min value that will ever be in a Order. Number
int maxNumber = 2500; // The max value that will ever be in a Order. Number
int curNumber = Integer.parseInt(orderNumber.replaceAll("\\D", ""));

if (orderNumber.matches("(?i)[SF]B\\d{3,}") && (curNumber >= minNumber && curNumber <= maxNumber)) {
    System.out.println("VALID!");
}
else {
    System.out.println("INVALID!");
}
  • Related