Guy
Guy

Reputation: 163

Java: Missing return statement error

I need to create a class of a country. one of it's attributes is an array of cities. I am required to write a method that can find the city's extension in the array when it's name is given (a name of a city is one of its attributes, and it can be reached by using the getCityName() method).

I wrote this code:

private int findCityExtensionByName (String cityName)
{
    for(int i=0 ; i<=MAXIMUM_NUMBER_OF_CITIES ;i++)
    {
        if (_cities[i].getCityName().equals(cityName))
            return i;      
    }
}

but I get this compliation error: "Missing return statement". I'm clueless in regards of how to fix this.

I'm sorry if this is unclear since this is my first time using this site.

Upvotes: 0

Views: 82

Answers (3)

Alexis C.
Alexis C.

Reputation: 93842

You need to add a return statement for each possible execution path of your method (nobody can guarantees that the for loop will be executed or that there's is a cityName equals to what you have in your array) :

private int findCityExtensionByName (String cityName)
{
    for(int i=0 ; i<=MAXIMUM_NUMBER_OF_CITIES ;i++)
    {
        if (_cities[i].getCityName().equals(cityName))
            return i;      
    }
    return -1;
}

Upvotes: 3

Jeroen Vannevel
Jeroen Vannevel

Reputation: 44439

You have to return a value or throw an exception in case nothing is found.

Either use a magical value or throw an appropriate exception like IllegalArgumentException.

private int findCityExtensionByName (String cityName)
{
    for(int i=0 ; i<=MAXIMUM_NUMBER_OF_CITIES ;i++)
    {
        if (_cities[i].getCityName().equals(cityName))
            return i;      
    }
    throw new IllegalArgumentException("Could not find the city");
}

A magical value is a value which you don't expect to be used and you'll use instead to represent "nothing". In your case the most common sense ones would be -1 and Integer.MIN_VALUE.

Upvotes: 1

Sage
Sage

Reputation: 15408

It is a compiler time error if a method declared with return type can complete normally: it must return a value with defined type. Hence it is not known in compile time if the for loop would get executed computing and comparing it's condition.

Upvotes: 0

Related Questions