2014-01-18 53 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块中也不会返回任何内容。由于你的方法是字符串返回类型....它必须返回字符串..

相关问题