缺少返回语句,但是返回语句在那里吗?

时间:2020-01-10 04:54:55

标签: java

我有一个if / else循环嵌套在for循环中,这段代码说它缺少return语句:

  public int size()
  {
      //Count until you find a place in the array that is empty, then return the number
      int count = 0;
      for (int i = 0; i < theArray.length; i ++)
      {
          count ++;
          if (theArray[i] == 0)
          {
              return count;
          }
          else
          {
                 return 0;
          }
      }
  }

但是,如果我这样移动申报表:

  public int size()
  {
      //Count until you find a place in the array that is empty, then return the number
      int count = 0;
      for (int i = 0; i < theArray.length; i ++)
      {
          count ++;
          if (theArray[i] == 0)
          {
              return count;
          }
      }
      return 0;
  }

错误消失了,但是没有给出正确的计数。

2 个答案:

答案 0 :(得分:4)

如果theArray.length为零,则根本不会执行循环的主体,也不会执行return语句。

此外,您的逻辑似乎有些怪异,而且似乎没有理由使用局部count变量。首先,如果没有空格或数组根本没有空格(长度为0),则必须确定该方法应返回什么。对于这两种情况,我建议返回-1。如果目标是返回第一个空白空间的索引(也将是第一个空白空间之前的非空空间的数量的计数),则可以尝试:

public int size(int[] array) {
    for (int i = 0; i < array.length; i++) {
        if (array[i] == 0) {
            return i;
        }
    }
    return -1;
}

答案 1 :(得分:2)

如果'theArray'的大小为0,则第一个示例中将没有return语句。