Federico Agudelo Mejia
Federico Agudelo Mejia

Reputation: 407

Why does the following method shows error of return type

public static int letterPosition(String word,char a)//returns the position of searched character
{

    int lenght=word.length();

    for (int i=0; i < lenght; i++)
    {

        if(word.charAt(i)==a)
        {
            return i;
        }

    }
}

Upvotes: 1

Views: 48

Answers (3)

Reid Barber
Reid Barber

Reputation: 101

Something must be returned, and your return statement is inside the 'if' statement, implying you have to enter the conditional statement to return something. You need to have a return option if the 'if' statement isn't executed.

You can fix this by adding an 'else if' statement after the 'if' statement.

Upvotes: 2

Vishal Gajera
Vishal Gajera

Reputation: 4207

please do something like,

public static int letterPosition(String word,char a)//returns the position of searched character
{
    int returnValue = -1;
    if(word != null){ //this will save us from NullPointerException...

    int lenght=word.length();

    for (int i=0; i < lenght; i++)
    {

        if(word.charAt(i)==a)
        {
            returnValue  = i;
            break;
        }

    } //end of for loop
  }//end of if - word != null 
  return returnValue;
}

Upvotes: 0

Elliott Frisch
Elliott Frisch

Reputation: 201399

You need to handle the possibility that the loop isn't entered (or if it is entered, that the character isn't found). Add something like

return -1;

at the end of the method (to handle when the character isn't present).

Upvotes: 2

Related Questions