2013-05-22 15 views
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; 
    } 
} 

謝謝。

+2

爲什麼你設置屬性作爲'私人set'多大的價值? –

+1

使用'setX'方法設置屬性而不是讓屬性設置器公開是什麼? –

+0

出於興趣,你爲什麼不公開你的公共屬性?設置哪些返回值可能[違反CQS](http://andreasohlund.net/2008/09/04/command-query-separation/) – StuartLC

回答

0

你在你的方法(setSpeedXsetSpeedY設置值,setPositionXsetPositionY),但不會返回任何內容。但方法的簽名有返回類型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; 
} 
1

您從未放過return語句,因此即使您聲明瞭應該使用的方法,也不會返回任何值。

有兩種方法來解決這個問題:

使該方法void

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

或返回值:

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

這的方式去爲所有方法,不只是setSpeedX

3

添加return到你的方法應該返回值,如:

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

或改變他們返回void

public void setPositionY(int newPositionY) 
{ 
    positionY = newPositionY; 
} 
+0

我已經解決了它。謝謝! – Guang

+0

@廣州如果您發現此答案最有幫助,請將其標記爲解決方案。另外,爲什麼沒有在這篇文章中使用較短的版本:return positionY = newPositionY? – slawekwin

+1

@slawekwin因爲它不可讀,所以很容易被誤解爲'positionY == newPositionY'。可讀性在代碼中非常重要。 –

0

要麼返回一個值

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

或者將方法改爲void

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

似乎沒有要在返回值

相關問題