Can someone please help me with some code I have it is supposed to check that the string being passed is of 2 string and 3 ints which works fine, but if the 1 int is a zero it doesn’t work
so if it was CM044 it won’t work, CM450 will work can someone please help.
public boolean checkModule(String Module) {
if(Module.length() == 5){
boolean hasString = false;
boolean hasInt = false;
String letters = Module.substring(0, 2);
Pattern p = Pattern.compile("^[a-zA-Z]+$");
Matcher m = p.matcher(letters);
if (m.matches()) {
hasString = true;
}
String numbers=Module.substring(2,5);
try {
int num = Integer.parseInt(numbers);
String n = num + "";
if (num >0 && n.length() == 3)
hasInt = true;
} catch (Exception e) {
}
if (hasInt && hasString) {
return true;
}
}else{
return false;
}
return false;
}
Thanks
If you are going to use regular expressions you should definitely stick with them and not vary in and out.
package com.examples; import java.util.regex.Matcher; import java.util.regex.Pattern; public class Main { /** * @param args */ public static void main(String[] args) { new Main(); } public Main() { String[] testInputs = new String[] {"CM045", "CM450"}; for(String input : testInputs) { System.out.println("The module " + input + " is " + (checkModule(input) ? "valid" : "invalid")); } } public boolean checkModule(String Module){ Pattern p = Pattern.compile("[A-Z]{2}[0-9]{3}"); Matcher m = p.matcher(Module.toUpperCase()); return m.matches(); } }