【问题标题】:Missing return statement in a method for loop循环方法中缺少返回语句
【发布时间】:2013-11-06 10:58:14
【问题描述】:

这是我的代码:

//method to rotate the picture
public static Picture modifyPicture (Picture p, int value)
{
 // get width and height of the picture
 int width = p.getWidth();
 int height = p.getHeight();
 System.out.println ("Picture has width of " + width + 
                     " and height of " + height);
 if (value == 1)
 {
  Picture p2 = new Picture (height, width);

  int x = -1;
  int y = -1;

  for  ( x = 0 ; x < width ;  ++x )
  {
   for ( y = 0 ; y < height ; ++y )
   {
     // access the original pixel
     Pixel pixel1 = p.getPixel (x, y);
     Color c1 = pixel1.getColor();

     // access the pixel to modify
     int modifyXPos = (height-1)-y;
     int modifyYPos = x;
     Pixel pixel4 = p2.getPixel (modifyXPos, modifyYPos);
     pixel4.setColor( c1 );
   }
  }
  return p2;
 }
 else if (value == 2)
 {
  Picture p2 = new Picture ( width , height);

  int x = -1;
  int y = -1;

  for  ( x = 0 ; x < width ;  ++x )
  {
   for ( y = 0 ; y < height ; ++y )
   {
     // access the original pixel
     Pixel pixel1 = p.getPixel (x, y);
     Color c1 = pixel1.getColor();

     // access the pixel to modify
     int modifyXPos = x;
     int modifyYPos = (height-1) - y;
     Pixel pixel4 = p2.getPixel (modifyXPos, modifyYPos);
     pixel4.setColor( c1 );
   }
  }
  return p2;
 }
 else
 {
  System.out.println ("Value out of range");
 }
}

}//课程结束

所以在倒数第二个分号处我收到错误“缺少返回语句”,我明白为什么。我只是不知道我将如何解决它。在“if”语句之前重写图片 p2 等将是无用的,因为坐标必须改变,所以除此之外,我不知道如何在最后放置一个 return 语句。请帮助,并感谢您的时间和答案!

【问题讨论】:

  • 添加返回 p;在最后一个括号之前。
  • 有效,我想我也明白为什么。非常感谢!

标签: java loops if-statement return-value


【解决方案1】:

它说缺少返回语句,因为您的方法名称

public static Picture modifyPicture (Picture p, int value)

表示你要返回一个 Picture 对象,但你不在“其他”情况之一,

else
{
   System.out.println ("Value out of range");
   return null;     // Notice this
}

因此在那里添加一个退货声明

【讨论】:

    【解决方案2】:

    如果您承诺返回 Picture,则必须返回 Picture 或抛出异常。

    你可以在方法的最后添加

    return null;
    

    或者你可以在结束时抛出异常。

    throw new IllegalArgumentException("Value out of range");
    

    如果您对异常一无所知,请使用return null,然后阅读 Java 中的异常和错误处理。

    【讨论】:

      【解决方案3】:

      请在else循环中添加return语句

      【讨论】:

        【解决方案4】:

        嘿,你错过了 else 块的 return 语句。如果不满足任何条件,则不返回任何内容。将 return 包含在 else 块中。

        尝试返回空对象。

        【讨论】:

          【解决方案5】:

          如果绝对有必要改变坐标,那么你的第一个代码块必须被执行并且'else'分支永远不会被触发,对吗? 然后,在 else 子句中,抛出一个 argumentException。或者,也许更好的是,删除 ELSE 并通过抛出 ArgumentException 来结束函数。

          【讨论】:

            猜你喜欢
            • 2017-05-15
            • 2015-08-11
            • 1970-01-01
            • 1970-01-01
            • 2013-03-10
            • 1970-01-01
            • 2014-06-06
            • 2016-01-30
            • 2014-03-22
            相关资源
            最近更新 更多