Home > Enterprise >  C# function to return array and write the array in the Console
C# function to return array and write the array in the Console

Time:10-31

This is a function to get integer numbers from Console, this parte works right. The trouble is in the part of write the values from the array.

Console.WriteLine("Function get numbers...");

static int[] numbers(int[] values){
    for(int ind = 0; ind < 10; ind  ){
        Console.WriteLine("Type a number: ");
        values[ind]= int.Parse(Console.ReadLine());
    }
    return values;
}
numbers(new int[10]);

for(int s= 1; s < 10; s  ){
    Console.WriteLine(numbers(new int[s]));
}

I I looked in the documentation but I didn't find a solution.

CodePudding user response:

Console.WriteLine("Function get numbers...");

static int[] numbers(int[] values){
    for(int ind = 0; ind < 10; ind  ){
        Console.WriteLine("Type a number: ");
        values[ind]= int.Parse(Console.ReadLine());
    }
    return values;
}
var values = numbers(new int[10]);

for(int s= 0; s < 10; s  ){
    Console.WriteLine(values[s].ToString()));
}

I think this works? I didn't try to parse it, it seems

CodePudding user response:

The simplest way to display an array is to use string.Join() to combine the elements of the array into one comma-separated string

int[] array = new int[] { 1,2,3,4,5 };
Console.WriteLine(string.Join(",", array));

with results

1,2,3,4,5

You can use Environment.NewLine instead of "," to place each value in a new line.

Also, note in your code you are using an array as an argument in your function, which fills in the array and then returns it. But you don't need to pass the array, just the desired size of the array

static int[] numbers(int count){
    int[] values = new int[count];
    for(int ind = 0; ind < 10; ind  ){
        Console.WriteLine("Type a number: ");
        values[ind]= int.Parse(Console.ReadLine());
    }
    return values;
}

int[] array = numbers(10);

or fill in however many elements there are in the array already

static void numbers(ref int[] values){
    for(int ind = 0; ind < 10; ind  ){
        Console.WriteLine("Type a number: ");
        values[ind]= int.Parse(Console.ReadLine());
    }
}

int[] array = new int[10];
numbers(ref array);

depending on how many times you are going to create a new array, or want to re-use an existing array over and over. The keyword ref is not required here because you can always modify the elements of an array, but it is added as a convention to indicate to the reader that the function numbers() indeed modifies the array argument.

Finally, I am going to explain line by line what is going on to demonstrate why the code isn't behaving as expected

  1. numbers(new int[10]); this creates a new array of 10 elements and passes it the function numbers() the result of the function is never assigned to a local variable and thus lost forever.
  2. for(int s= 1; s < 10; s ){ ... } this is a loop for 9 iterations (1 to 9).
  3. Console.WriteLine(numbers(new int[s])); this creates a new array with s elements (again 1 to 9) and passes it to the function. The result of the function is passed to the WriteLine() method where the default behavior of arrays is to display the type and not the contents of the argument.

Possible fix to the above is to create the array once and access its elements in a loop (using the first update to numbers() from above)

int[] array = numbers(10);
for(int s= 0; s < array.Length; s  ){
    Console.WriteLine(array[s]);
}

Note that the iteration count is driven by array.Length instead of the hard-coded number 10.

CodePudding user response:

Here is an example:

static void Main(string[] args)
            {
                int stop = 0;
                int[] chosenNum = new int[6];
                while (stop == 0)
                {
                    Console.Clear();
                    string con = "";
                    Console.WriteLine("Enter six numbers between 1-100 separated by a comma with no duplicates:");
                    string numbers = Console.ReadLine();
                    string[] userNumbers = numbers.Replace(" ", "").Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries).ToArray();;//remove ex: ,, issues
                    string[] checkDup = userNumbers.Distinct().ToArray();//remove duplicates
                    if (userNumbers.Count() < 6)
                    {
                        Console.WriteLine("You entered less than six numbers");
                        Console.WriteLine("Try Again Y or N");
                        con = Console.ReadLine();
                        if (con.ToUpper() != "Y")
                        {
                            stop = 1;
                        }
                    }
                    else if (userNumbers.Count() > 6)
                    {
                        Console.WriteLine("You entered more than 6 numbers");
                        Console.WriteLine("Try Again Y or N");
                        con = Console.ReadLine();
                        if (con.ToUpper() != "Y")
                        {
                            stop = 1;
                        }
                    }
                    else if (checkDup.Count() < 6)
                    {
                        Console.WriteLine("You entered duplicate numbers");
                        Console.WriteLine("Try Again Y or N");
                        con = Console.ReadLine();
                        if (con.ToUpper() != "Y")
                        {
                            stop = 1;
                        }
                    }
                    else if (!IsNumeric(userNumbers))
                    {
                        Console.WriteLine("You entered non-numeric value(s)");
                        Console.WriteLine("Try Again Y or N");
                        con = Console.ReadLine();
                        if (con.ToUpper() != "Y")
                        {
                            stop = 1;
                        }
                    }
                    else if (IsInRange(userNumbers) < 6)
                    {
                        Console.WriteLine("You entered out of range value(s)");
                        Console.WriteLine("Try Again Y or N");
                        con = Console.ReadLine();
                        if (con.ToUpper() != "Y")
                        {
                            stop = 1;
                        }
                    }
                    else
                    {
                        var lowerBound = 1;
                        var upperBound = 100;
                        var random = new Random();
                        int[] randomNum = new int[6];
                        int count = 0;
                        foreach(string str in userNumbers){
                            var rNum = random.Next(lowerBound, upperBound);
                            randomNum[count] = rNum;
                            count  ;
                            
                        }
                        
                        string[] ourPicks = Array.ConvertAll(randomNum, s => s.ToString()).ToArray();
                        Array.Sort(userNumbers);
                        Array.Sort(ourPicks);
                        //string[] ourpicks = { "1", "2" };//for testing
                        Console.WriteLine("Your Numbers: {0}", string.Join(", ", userNumbers));
                        Console.WriteLine("Our Numbers: {0}", string.Join(", ", ourPicks));
                        string[] result = userNumbers.Intersect(ourPicks).ToArray();
                        if(result.Count() > 0)
                        {
                            Console.WriteLine("Matchs: {0}", string.Join(", ", result));
                        }
                        else
                        {
                            Console.WriteLine("Match's = 0");
                        }
                        stop = 1;
                    }
    
                    
    
                }
    
                Console.ReadLine();
    
    
    
    
    
            }
    
            public static bool IsNumeric(string[] num)
            {
    
                foreach (string str in num)
                {
                    bool check = int.TryParse(str, out int test);
    
                    if (!check)
                    {
                        return false;
                    }
                }
                return true;
    
            }
    
            public static int IsInRange(string[] num)
            {
                int count = 0;
                foreach (string str in num)
                {
                    int.TryParse(str, out int test);
    
                    if (test > 0 & test <= 100)
                    {
                        count  ;
                    }
                }
                return count;
            }
  • Related