Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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));
        
    }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading