so what I'm trying to do is to write code that checks whether any of two actual parameters of type String contain one of two illegal characters, and if so, to throw an exception which states which one of the two characters it is and the index in which it is located. The only way I can think of doing it is to create a bunch of if statements, to check for each individual case:
if (firstName.contains("!") || firstName.contains(":") || lastName.contains("!") || lastName.contains(":")){
if (firstName.contains("!"))
throw new BadCharException('!', firstName.indexOf('!'));
if (firstName.contains(":"))
throw new BadCharException(':', firstName.indexOf(':'));
if (lastName.contains("!"))
throw new BadCharException('!', lastName.indexOf('!'));
if (lastName.contains(":"))
throw new BadCharException(':', lastName.indexOf(':'));
Is there a cleaner or better or more efficient way of going about this?
CodePudding user response:
Here's a more cleaner way:
char[] unwantedChars = {'!', ':'};
for(char character: unwantedChars) {
if(firstName.contains(character))
throw new BadCharException(character, firstName.indexOf(character));
if(lastName.contains(character))
throw new BadCharException(character, lastName.indexOf(character));
}