Ad
Check For An Unwanted Character To Throw A BadCharException
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?
Ad
Answer
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));
}
Ad
source: stackoverflow.com
Related Questions
- → I can't convert Json to string [OctoberCms]
- → Passing a JS var from AJAX response to Twig
- → how to convert stdclass into string
- → Dynamic url segment name in laravel 5.1
- → Knockout JS - How to return empty strings for observable fields
- → How to replace *( in a string
- → Removing a JavaScript property inside a specific Object within an Array
- → Is this considered to be a custom facade approach in Laravel?
- → JavaScript: How would I reverse ONLY the words in a string
- → How to access a complex object comming from a datatable cell in JQuery/Javascript
- → Regex extract string after the second "." dot character at the end of a string
- → Htaccess negation
- → Convert generic text string in json object into valid url using Angular
Ad