无法将类型隐式转换为int []

时间:2015-07-15 06:38:29

标签: c#

我正在尝试制作一个策划游戏,我让用户猜测4-10而不是颜色之间的数字序列,但出于某种原因我的GetRandomNumberCount会收到错误:

  

无法将类型隐式转换为int []

任何指导都将不胜感激

// This method gets the quantity of random numbers to use in the game. 
public static int GetRandomNumberCount(int difficulty)
{
    int[] randomNumber = 0;   

    if(difficulty == 1)
    {
       randomNumber= GenerateRandomNumber(0, 4);
    }
    else if(difficulty == 2)
    {
       randomNumber = GenerateRandomNumber(1, 6);
    }
    else if (difficulty == 3)
    {
       randomNumber = GenerateRandomNumber(1, 11);
    }

      return randomNumber;
}
// This method generates the random numbers for the array of numbers. 
public static int[] GenerateRandomNumber(int min, int max)
{   
    // this declares an integer array with 5 elements
    // and initializes all of them to their default value
    // which is zero
    int[] test2 = new int[5];

    Random randNum = new Random();
    for (int i = 0; i < test2.Length; i++)
    {
        test2[i] = randNum.Next(min, max);
    }
    return test2;
}

3 个答案:

答案 0 :(得分:2)

GetRandomNumberCount方法返回int,而不是int[] GenerateRandomNumber返回数组int[];似乎你必须这样做 GenerateRandomNumber获取项目

public static int GetRandomNumberCount(int difficulty) {
  if (difficulty == 1)
    return GenerateRandomNumber(0, 4)[0]; // just 1st item
  else if (difficulty == 2)
    return GenerateRandomNumber(1, 6)[0];
  else if (difficulty == 3)
    return GenerateRandomNumber(1, 11)[0]; 
  else
    return 0;
}

或者如果要返回数组,则必须修改GetRandomNumberCount

// note int[] - it's an array that is returned
public static int[] GetRandomNumberCount(int difficulty) {
  if (difficulty == 1)
    return GenerateRandomNumber(0, 4);
  else if (difficulty == 2)
    return GenerateRandomNumber(1, 6);
  else if (difficulty == 3)
    return GenerateRandomNumber(1, 11); 
  else
    return new int[5]; // 5 zero items
}

答案 1 :(得分:1)

对方法import socket file = 'ServerList' f = open(file, 'r') lines = f.readlines() f.close() for i in lines: host = i.strip() try: val1 = socket.gethostbyaddr(host) print("%s - %s" % (host, val1)) except socket.error, exc: print ("%s - No Entry, socket error: %s" % (host, exc)) 的Cahnge声明。

GetRandomNumberCount

目前,您正在从方法返回public static int[] GetRandomNumberCount(int difficulty) ,并且array of int方法是单return type。因此,将其更改为返回int的{​​{1}}。

答案 2 :(得分:0)

你错过了一些非常重要的事情。您已声明和数组,并且您正在尝试为数组类型分配,因此可以尝试此randomNumber [0] =您的数字