How to fix this? Or, why is this error showing up. What am I doing wrong. I understand that there is some issue with the datatype but why and what can I do to resolve this?
My C# code:
int[] nums = new int[5];
int i = 0;
while (i < 5)
{
int num = Convert.ToInt32(Console.ReadLine());
if (Array.Find(nums, num) != 0)
{
Console.WriteLine("Error: Number already inputed. Try a different number.");
continue;
}
i ;
}```
Error:
*Severity Code Description Project File Line Suppression State
Error CS1503 Argument 2: cannot convert from 'int' to 'System.Predicate<int>' udemy lectures beginner section6 exercise D:\C# practice\C# practice codes\exercises\udemy lectures beginner section6 exercise\udemy lectures beginner section6 exercise\Program.cs 104 Active* (line 8)
CodePudding user response:
you can create predicate like this
if (Array.Find (nums, n=> n== num) >= 0)
{
...
but it is usually used of array of complicated objects. For a simple array like yours it's better to use
if (Array.IndexOf(nums, num) != -1)
{
...
CodePudding user response:
So, I assume that you want to check for duplicates in your array. You only want to add unique inputs to your array,so every number is supposed to be only once in the array, right? Then, the thing you are doing wrong, is that you are trying to overload an int to Array.Find. I guess you want to check if the int is contained within the array. But the type you actually have to use is a predicate. A predicate is nothing more than a Func - a function delegate returning a bool. The proper way to use the find function is to write it as follows.
Array.Find(nums,x => x== num);
Your code should noe look like this.
int[] nums = new int[5];
int i = 0;
while (i < 5)
{
int num = Convert.ToInt32(Console.ReadLine());
if (Array.Find(nums, num) != 0)
{
Console.WriteLine("Error: Number already inputed. Try a different
number.");
continue;
}
i ;
}
But, by using find you are passing a function. This is not the most performant way to solve this problem and you are, as @UnHolySheep already pointed out, probably better up by just checking Indexof(num) != -1.