0

下划线表示错误“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;
    }
}

谢谢你。

4

4 回答 4

3

添加return到应该返回值的方法中,例如:

public int setPositionY(int newPositionY)
{
    positionY = newPositionY;
    return positionY;
}

或将它们更改为 return void

public void setPositionY(int newPositionY)
{
    positionY = newPositionY;
}
于 2013-05-22T06:39:10.620 回答
1

您从不添加return语句,因此即使您声明了它应该声明的方法,也不会返回任何值。

有两种方法可以解决此问题:

制作方法void

public void setSpeedX(int newSpeedX)
{
    speedX = newSpeedX;
}

或返回一个值:

public int setSpeedX(int newSpeedX)
{
    speedX = newSpeedX;
    return speedX;
}

顺便说一句,这适用于所有方法,而不仅仅是setSpeedX.

于 2013-05-22T06:38:48.797 回答
0

您正在方法中设置一个值(setSpeedX, setSpeedY, setPositionX, setPositionY),但没有返回任何内容。但是方法的签名有一个返回类型int

所以...用 替换返回类型intvoid如下所示:

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

或返回 type 的值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;
}
于 2013-05-22T06:40:12.017 回答
0

要么返回一个值

public int setSpeedX(int newSpeedX)
{
    speedX = newSpeedX;
    return(speedX);
}

或者改变方法为void

public void setSpeedX(int newSpeedX)
{
    speedX = newSpeedX;
}

返回值似乎没有多大价值

于 2013-05-22T06:45:06.263 回答