setSpeedX
标有“不是所有代码路径都返回值”的错误。我可以知道如何解决它吗?代码如下:
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;
}
}
谢谢。
答案 0 :(得分:3)
将return
添加到应返回值的方法中,如:
public int setPositionY(int newPositionY)
{
positionY = newPositionY;
return positionY;
}
或更改它们以返回void
:
public void setPositionY(int newPositionY)
{
positionY = newPositionY;
}
答案 1 :(得分:1)
你永远不会输入return
语句,所以即使你声明了它应该的方法,也不会返回任何值。
有两种方法可以解决这个问题:
制作方法void
:
public void setSpeedX(int newSpeedX)
{
speedX = newSpeedX;
}
或返回一个值:
public int setSpeedX(int newSpeedX)
{
speedX = newSpeedX;
return speedX;
}
顺便说一句,这适用于所有方法,而不仅仅是setSpeedX
。
答案 2 :(得分:0)
您在方法中设置了一个值(setSpeedX
,setSpeedY
,setPositionX
,setPositionY
),但没有返回任何内容。但是方法的签名具有返回类型int
。
所以......用int
替换返回类型void
,如下所示:
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;
}
答案 3 :(得分:0)
返回值
public int setSpeedX(int newSpeedX)
{
speedX = newSpeedX;
return(speedX);
}
或者将方法更改为无效
public void setSpeedX(int newSpeedX)
{
speedX = newSpeedX;
}
返回值似乎没什么价值