I'm not sure if I'm checking in the wrong area or if my code to check is wrong. I am attempting to check if employee Id is valid in format 999-A. Any help would be appreciated.
public class Employee {
private String name;
private String employeeNumber;
private String hireDate;
// Constructor
public Employee(String name, String employeeNumber, String hireDate){
this.name = name;
if(isValidEmployeeNumber(employeeNumber) == true){
this.employeeNumber = employeeNumber;
} else{
}
this.hireDate = hireDate;
}
// Getters and Setters
public String getName(){
return name;
}
public String getEmployeeNumber(){
return employeeNumber;
}
public String getHireDate(){
return hireDate;
}
public void setName(String name){
this.name = name;
}
public void setEmployeeNumber(String employeeNumber){
this.employeeNumber = employeeNumber;
}
public void setHireDate(String hireDate){
this.hireDate = hireDate;
}
//999-X
private boolean isValidEmployeeNumber(String employeeNumber){
if(Character.getNumericValue(employeeNumber.charAt(4)) > 10 &
Character.getNumericValue(employeeNumber.charAt(4)) < 22)
{
/*
int cutNum = Integer.parseInt(employeeNumber.substring(0,1));
if(cutNum <= 0 && cutNum <= 9){
cutNum = Integer.parseInt(employeeNumber.substring(1, 2));
if(cutNum <= 0 && cutNum <= 9){
cutNum = Integer.parseInt(employeeNumber.substring(2, 3));
if(cutNum <= 0 && cutNum <= 9){
setEmployeeNumber(employeeNumber);
return true;
}
}
}*/
return true;
}
return false;
}
}
As you can see I commented out the part that I have attempted even when commenting it out the employeeNumber is coming out null. I have attempted string.matches("\d{1}\d{1}\d{1}\-\D{1}") and a few other strategies.
Regular expressions are a very good fit for this task:
private boolean isValidEmployeeNumber(String employeeNumber) {
return employeeNumber.matches("[0-9]{3}-[A-Z]")
}
To break down the regular expression:
[0-9]{3}
a number (0-9) 3 times-
the dash[A-Z]
A-Z onceanything else wouldn't be valid. Note \D
would be valid for any non-number, which I don't think what you intended.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments