2014-01-18 51 views
-4

好吧,我發現了一個無法訪問的代碼,而不是所有的代碼路徑從代碼可達代碼,而不是所有的代碼路徑返回一個值

private string MoveForward() 
{ 
    //if current direction is east, GetRoomEast 
    if (Player.CurrentDirection == "EAST") 
    { 
     return GetroomEast(); 

     if (Player.NextMove != "") 

     { 
      Player.Y++; 
     } 
     else 
     { 
      Console.WriteLine("You Bumped into a Wall"); 
     } 
     //if GetRoomEast is not "", then playercol = playercol+1; 
     //if current direction is west... 
    } 
} 

該塊返回值,我在上面初始化的變量是

public struct DragonPlayer 
{ 
    public int X, Y; 
    public string CurrentDirection; 
    public string NextMove; 
} 

public class DragonGameboard 
{ 
    public string[,] GameboardArray; 
    public DragonPlayer Player; 
    private Random r; 

    public DragonGameboard() 
    { 
     GameboardArray = new string[4, 4]; 
     Player.CurrentDirection = "EAST"; 
     Player.NextMove = ""; 
     r = new Random(); 
     Player.X = r.Next(0, 4); 
     Player.Y = r.Next(0, 4); 
     GenerateRandomBoard(); 
    } 
} 

爲什麼這樣做?我確定它必須是非常愚蠢的東西,但我很難弄清楚它是什麼?

+0

我的意思是我得到這些錯誤的頂部。 – user3196400

+5

你嘗試過研究錯誤嗎?它幾乎總結了這一點:您不返回所有代碼路徑的值,而返回類型爲「string」,而「無法訪問的代碼」意味着該代碼將永遠不會到達,因爲您返回之前。 – CodeCaster

+0

@CodeCaster使用Google的Beucase比要求堆棧溢出更難':)' –

回答

0

代碼的每條路徑都必須返回string類型的值。另外,你的代碼永遠不會執行,即:

if (Player.NextMove != "") 
{ 
    Player.Y++; 
} 

else 
{ 
    Console.WriteLine("You Bumped into a Wall"); 
} 

你已經返回了一個值,所以沒有執行任何操作。

此外,導致函數結束的每個路徑都返回一個值。從邏輯上瀏覽代碼並找出場景,你會發現很多。

也許我會建議慢慢學習基礎知識,因爲這些錯誤對於任何編程語言都是非常重要的+您已經收到了這條消息,這很清楚。編程遊戲對於程序員來說並不是一個很好的起點。

1

您從功能時,您如果語句之前回來,它永遠不會給你的,如果你statement.Therefore if語句成爲可達代碼

return GetroomEast(); 

     if (Player.NextMove != "") 

if語句後,您應該把這個return語句。

+0

這不會修復「不是所有的代碼路徑返回值」錯誤 –

0

你定義了你的MoveForward()轉發方法來返回一個字符串,但你沒有返回一個。將定義更改爲:

private void MoveForward(); 

...或者返回一個字符串。

+0

但他已經返回GetroomEast();我會說他正在嘗試返回一些東西。 –

0

我在代碼中添加了註釋,以向您說明爲什麼有無法訪問的代碼以及爲什麼所有代碼​​路徑都不返回值。

private string MoveForward() 
{ 
    if (Player.CurrentDirection == "EAST") 
    { 
     return GetroomEast(); //Once you return the value here it ends the call. 

     if (Player.NextMove != "") //This line (or anything below it) will never run. 
     { 
      Player.Y++; 
     } 
     else 
     { 
      Console.WriteLine("You Bumped into a Wall"); 
     } 
     //if GetRoomEast is not "", then playercol = playercol+1; 
     //if current direction is west... 
    } 

    //We reach here if Player.CurrentDirection does not equal "EAST" 
    //As there is no more code there is no returned value. 
    //You would need to do something like return NoValidMove() 
} 
0

這條線之後,return GetroomEast()執行被跳傘循環的,因此,U越來越不到的代碼錯誤。在下一個if,else塊中也不會返回任何內容。由於你的方法是字符串返回類型....它必須返回字符串..

相關問題