String name;
void checkName(String name) throws IllegalArgumentException {
// no name can be less than two characters
if (name.length < 2) {
throw new IllegalArgumentException("The name is too short, it must be at least two characters");
}
// a name can only contain letters, spaces and hyphens
for (int i = 0; i < name.length(); i++) {
char c = name.charAt(i);
if (! (Character.isLetter(c) || c == ' ' || c == '-')) {
throw new IllegalArgumentException("'" + c + "' is an illegal character, a name can only contain letters, space or hyphens");
}
}
}
void setName(String name) {
checkName(name);
this.name = name;
} |