并非所有代码路径都返回“值”

本文关键字:返回 路径 代码 | 更新日期: 2023-09-27 18:02:38

嗨,我试图使一个策划者的游戏,我让用户猜测4-10之间的数字序列,而不是颜色,但出于某种原因,我的GetRandomNumberCount和我的GenerateRandomNumber给我的错误不是所有的代码路径返回一个值。

如有任何指导,将不胜感激

public static int GetRandomNumberCount()
{
      //Create the secret code
      Random RandomClass = new Random();
      int first = RandomClass.Next(1, 5);
      int second = RandomClass.Next(1,5);
      int third = RandomClass.Next(1,5);
      int forth = RandomClass.Next(1,5);
      Console.WriteLine ("You are playing with M@sterB@t");
      Console.WriteLine ("Bot Says : You Go First");
      Console.WriteLine("Game Settings ");
      Console.WriteLine("The Game Begins");
}

并非所有代码路径都返回“值”

这是因为它们不返回值。例如,GetRandomNumberCount将Int设置为其返回类型,但没有返回语句。如果你不想返回任何东西,将返回类型设置为void。以这个为例

 public static int[] GetRandomNumberCount()
{
    //Create the secret code
    Random RandomClass = new Random();
    int first = RandomClass.Next(1, 5);
    int second = RandomClass.Next(1,5);
    int third = RandomClass.Next(1,5);
    int forth = RandomClass.Next(1,5);
    Console.WriteLine ("You are playing with M@sterB@t");
    Console.WriteLine ("Bot Says : You Go First");
    Console.WriteLine("Game Settings ");
    Console.WriteLine("The Game Begins");
    //This is where you would return a value, but in this case it seems you want to return an array of ints
    //Notice how I changed the return type of the method to Int[]
   int[] numbers = new int[4];
   numbers.Add(first);
   numbers.Add(second);
   numbers.Add(third);
   numbers.Add(fourth);
   //This is the actual return statement that your methods are missing
   return numbers;
    }

不管你是否真的想返回一个int数组是没有意义的,我只是猜测。真正值得注意的是

中的int[]
public static int[] GetRandomNumberCount()

声明了一个返回类型,这意味着需要一个返回语句。

你正在得到这个错误,因为你的方法签名说它返回一个int,但你没有返回任何东西。我看到的是,您的意思是有一个void返回类型的方法,因为您只是打印

public static void GetRandomNumberCount()
{
      //Create the secret code
      Random RandomClass = new Random();
      int first = RandomClass.Next(1, 5);
      int second = RandomClass.Next(1,5);
      int third = RandomClass.Next(1,5);
      int forth = RandomClass.Next(1,5);
      Console.WriteLine ("You are playing with M@sterB@t");
      Console.WriteLine ("Bot Says : You Go First");
      Console.WriteLine("Game Settings ");
      Console.WriteLine("The Game Begins");
}