I am trying to make a mastermind game where I having the user guess a number sequence between 4-10 instead of colours but for some reason my GetRandomNumberCount
gets the error:
Cannot implicitly convert type to int[]
Any guidance would be appreciated
// 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;
}
The GetRandomNumberCount
method returns int
, not int[]
while GenerateRandomNumber
returns an array : int[]
; seems that you have to get an item from 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;
}
or if you want to return an array, you have to modify 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
}
Cahnge declaration of method GetRandomNumberCount
to this.
public static int[] GetRandomNumberCount(int difficulty)
Currently you are returning array of int
from method and return type
of method is a single int
. So change it to return array
of int
.
You're missing something very important. You've declared and array and you're trying to assign an to the array type so maybe try this randomNumber[0]=YOUR NUMBER
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.