Question

I've written up some code that checks 2 intervals which have x and y values, and check to see if they're overlapping, and I'm havign an issue with the return of the toString method:

public String toString() {
    if (isEmpty()) {
        String result = String.format("Interval: (EMPTY)");
    } else {
        String result = String.format("Interval: [%s, %s]", Double.toString(left),
                Double.toString(right));
    }
    return result;
}

}

I get the error "result cannot be resolved to variable" and I'm not sure why, as the if function returns a string either way, and this is what is expected of the return type of the string, so I'm really confused and not sure if i'm just missing something stupid.

Was it helpful?

Solution

You're declaring result inside the scope of either the if statement or the else block. Once the code exits those blocks, your result variable is no longer in scope.

To fix it, simply declare your variable at the correct scope:

public String toString() {

    String result;

    if (isEmpty()) {
        result = String.format("Interval: (EMPTY)");
    } else {
        result = String.format("Interval: [%s, %s]", Double.toString(left),
                Double.toString(right));
    }
    return result;
}

Or just use the return statement in-line:

public String toString() {

    if (isEmpty()) {
        return String.format("Interval: (EMPTY)");
    } else {
        return String.format("Interval: [%s, %s]", Double.toString(left),
                Double.toString(right));
    }

}

OTHER TIPS

This is a scope problem. The result variable is only declared in the if statement, that is to say, it's only declared if isEmpty() returns true. To fix this, declare the variable above the if-else block like this:

public String toString() {
    String result;
    if (isEmpty()) {
        result = String.format("Interval: (EMPTY)");
    } else {
        result = String.format("Interval: [%s, %s]", Double.toString(left),
        Double.toString(right));
    }

    return result;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top