【问题标题】:Why does the following method shows error of return type为什么以下方法显示返回类型错误
【发布时间】:2015-11-28 21:34:35
【问题描述】:
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;
        }

    }
}

【问题讨论】:

  • 它不处理从未找到字符的情况。
  • 下面有三个答案,这些都有用吗?请考虑接受其中一个作为答案,如果是,请单击最有用的选项旁边的勾号。

标签: java methods return


【解决方案1】:

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

return -1;

在方法结束时(当字符不存在时处理)。

【讨论】:

    【解决方案2】:

    必须返回一些东西,并且你的返回语句在'if'语句中,这意味着你必须输入条件语句才能返回一些东西。如果未执行“if”语句,您需要有一个返回选项。

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

    【讨论】:

      【解决方案3】:

      请做类似的事情,

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2022-01-14
        • 2022-06-15
        • 1970-01-01
        • 2018-05-29
        • 1970-01-01
        • 2023-03-18
        • 1970-01-01
        相关资源
        最近更新 更多