如何解决此错误“并非所有代码路径都返回值”?
本文关键字:代码 路径 返回值 何解决 解决 错误 | 更新日期: 2023-09-27 18:14:51
setSpeedX
下划线表示错误"not all code paths return a value"。我能知道怎么解吗?代码如下:
class Ball
{
public int speedX { get; private set; }
public int speedY { get; private set; }
public int positionX { get; private set; }
public int positionY { get; private set; }
public Ball(int speedX, int speedY, int positionX, int positionY)
{
this.speedX = speedX;
this.speedY = speedY;
this.positionX = positionX;
this.positionY = positionY;
}
public int setSpeedX(int newSpeedX)
{
speedX = newSpeedX;
}
public int setSpeedY(int newSpeedY)
{
speedY = newSpeedY;
}
public int setPositionX(int newPositionX)
{
positionX = newPositionX;
}
public int setPositionY(int newPositionY)
{
positionY = newPositionY;
}
}
谢谢。
将return
添加到应该返回值的方法中:
public int setPositionY(int newPositionY)
{
positionY = newPositionY;
return positionY;
}
或将它们更改为返回void
:
public void setPositionY(int newPositionY)
{
positionY = newPositionY;
}
您从未放入return
语句,因此没有返回值,即使您声明了应该返回值的方法。
使方法void
:
public void setSpeedX(int newSpeedX)
{
speedX = newSpeedX;
}
或返回值:
public int setSpeedX(int newSpeedX)
{
speedX = newSpeedX;
return speedX;
}
这适用于所有方法,而不仅仅是setSpeedX
。
您正在方法(setSpeedX
, setSpeedY
, setPositionX
, setPositionY
)中设置值,但不返回任何内容。但是方法的签名有一个返回类型int
。
所以…用void
替换返回类型int
,如下所示:
public void setSpeedX(int newSpeedX)
{
speedX = newSpeedX;
}
public void setSpeedY(int newSpeedY)
{
speedY = newSpeedY;
}
public void setPositionX(int newPositionX)
{
positionX = newPositionX;
}
public void setPositionY(int newPositionY)
{
positionY = newPositionY;
}
或返回int
类型的值,如下所示:
public int setSpeedX(int newSpeedX)
{
speedX = newSpeedX;
return speedX;
}
public int setSpeedY(int newSpeedY)
{
speedY = newSpeedY;
return speedY;
}
public int setPositionX(int newPositionX)
{
positionX = newPositionX;
return positionX;
}
public int setPositionY(int newPositionY)
{
positionY = newPositionY;
return positionY;
}
返回一个值
public int setSpeedX(int newSpeedX)
{
speedX = newSpeedX;
return(speedX);
}
或者将方法更改为void
public void setSpeedX(int newSpeedX)
{
speedX = newSpeedX;
}
返回值