为什么以下方法显示返回类型的错误

时间:2015-11-28 21:34:35

标签: java methods return

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;
        }

    }
}

3 个答案:

答案 0 :(得分:2)

您需要处理循环未输入的可能性(或者如果输入循环,则表示找不到该字符)。添加类似

的内容
return -1;

在方法的最后(处理角色不存在时)。

答案 1 :(得分:2)

必须返回一些内容,并且您的return语句位于'if'语句中,这意味着您必须输入条件语句才能返回一些内容。如果未执行'if'语句,则需要返回选项。

您可以通过在'if'语句后添加'else if'语句来解决此问题。

答案 2 :(得分:0)

请做点什么,

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;
}
相关问题