0

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.

1
  • 1
    Thank you all for the great answers! your help is muchly appreciated. Commented Dec 12, 2013 at 0:00

3 Answers 3

3

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;
}
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

0

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.

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.