0

In the following code I check whether or not the given url ends with an allowed filetype (possible types: .jpg, .jpeg, .png & .gif). The list of types are saved in an arraylist which holds the textual description from the UI (e.g. "JPG Images").

My intention is to make the function traverse trough the list with descriptions and check the url with their corresponding URL check methods.

I expected this code to work as I believe that every scenario has been accounted for: if it's JPG, PNG or GIF it returns true, otherwise it returns false. It remains with an error though:

Exception in thread "AWT-EventQueue-0" java.lang.Error: Unresolved compilation problem: 
This method must return a result of type boolean

Which obviously means that the returns somewhere have gone wrong. What am I overlooking?

private boolean isImageURL(ImageURL url) {
    for (String type : fileTypes) {
        if (type.equalsIgnoreCase("JPG Images")) {
            if (url.isJPG() || url.isJPEG()) {
                return true;
            }
        } else if (type.equalsIgnoreCase("PNG Images")) {
            if (url.isPNG()) {
                return true;
            }
        } else if (type.equalsIgnoreCase("GIF Images")) {
            if (url.isGIF()) {
                return true;
            }
        } else {
            return false;
        }
    }
}

3 Answers 3

6

All the possible execution paths are not covered. For example, if the type is "JPG Images", but the url is neither JPG nor JPEG, the method doesn't return anything.

Remove the last else clause, and simply return false at the end of the method.

Sign up to request clarification or add additional context in comments.

2 Comments

@colinjameswebb please elaborate?
@owlstead if fileTypes is an iterable, with a size of zero, the code inside the for loop will never get run.
4

Well, simple, if one of the embedded "leaf" if statements returns false for the expression, then the application does not get to a return statement. The for loop may not be executed either.

To resolve the issue, move the return false to the end of the method, and you should be all right.

Comments

0

Here's one of your ifs:

    else if (type.equalsIgnoreCase("PNG Images")) {
        if (url.isPNG()) {
            return true;
        }
        //otherwise... return what? (error here, put return false here)
    }

You could also get rid of the last else and just return false.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.