Home > Net >  Best way to store user input from loop for further operations in another method
Best way to store user input from loop for further operations in another method

Time:11-13

This just an example, I would like to be able to use the stored values from the array inside the first method in the second method to find the arithmetic mean, the problem is how do I access it? Or is the array itself a wrong solution?

using System;
namespace arithmetic_mean
{
    class Program

    {
        static void Main(string[] args)

        {
            Console.WriteLine("How many decimal numbers do you plan to enter?");
            string userInput = Console.ReadLine();
            int num_user;
            int.TryParse(userInput, out num_user);

            first_method(num_user);
        }

        static void first_method(int num_user)
        {
            string[] newarray = new string[num_user];
            for (int i = 0; i < num_user; i  )
            {
                Console.WriteLine("Enter a decimal number:");
                newarray[i] = Console.ReadLine();
            }
        }

        static void second_method(string newarray)
        {
            Convert.ToDouble(newarray);
            // get arithmetic_mean
        }

    }
}

CodePudding user response:

Theres a lot of issues with your code regarding style and best design practices. I won't get into that here and just focus on the question: How do I use the array from first_method somewhere besides first_method?

There are a few ways to use values from one method in another. The simplest way is via the return value. I've rewritten first_method to return the array:

static string[] first_method(int num_user) // The signature changed: void -> string[]
{
    string[] newarray = new string[num_user];
    for (int i = 0; i < num_user; i  )
    {
        Console.WriteLine("Enter a decimal number:");
        newarray[i] = Console.ReadLine();
    }

    return newarray; // Added this line.
}

So now you can use that array in Main:

static void Main(string[] args)

{
    Console.WriteLine("How many decimal numbers do you plan to enter?");
    string userInput = Console.ReadLine();
    int num_user;
    int.TryParse(userInput, out num_user);

    string[] inputs = first_method(num_user); // The return value of first_method is now stored.

    // Now it's possible to use the array in second_method:
    foreach(var input in inputs)
        second_method(input);
}

Again, theres a litany of other issues with your code, but you're clearly new to this. I hope to see you get better in the near future!

CodePudding user response:

In general case you can just enumerate values without storing them (imagine that you get values from, say, a database and you have 10 billion of them), i.e.

  using System.Collections.General;
  using System.Linq;

  ... 

  static IEnumerable<double> first_method(int num_user) {
    // for eaxh user
    for (int i = 0; i < num_user;   i) {
      // we keep asking until valid value is provided
      while (true) {
        Console.WriteLine($"For user #{i   1} enter a decimal number: ");

        if (double.TryParse(Console.ReadLine(), out var result)) {
          // we return result and keep on doing for the next user
          // note yield return, not return
          yield return result;

          break;
        }

        Console.WriteNumber("Syntax error. Please, repeat again"); 
      }
    }
  }

Then whenever you want a collection you can materialize the enumeration:

  double[] data = first_method(num_user).ToArray();

If you want to compute arithmetic mean

  static void second_method(int num_user)
  {
     double mean = first_method(num_user).Average();    
      ... 
  }

Or even, without second_method

   static void Main(string[] args)
   {
        int num_user; 

        do { // keep asking until correct value provided
            Console.WriteLine("How many decimal numbers do you plan to enter?");
            string userInput = Console.ReadLine();
        } 
        while(!int.TryParse(userInput, out num_user) && num_user > 0);

        double mean = first_method(num_user).Average();  

        Console.WriteLine($"users: {num_user}, mean: {mean}"); 
    }

CodePudding user response:

Create a List Add them in there and pass that to the method. Easiest, Clear, simple.

CodePudding user response:

I belive best approach is to make small methods which do take arguments and return results of operation. In below example you can see that in Main method there are 3 lines of code which are high level description what program should do. Read numbers from console, then calculate mean, and print mean to console.

Methods like ReadNumberFromConsole have well defined name so you can understand what it does even without reading it's code. Result of work is returned so it can be passed to next method. This way you can easily test and modify code if you need.

using System;

namespace ConsoleApp7
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            decimal[] numbers = ReadNumbersFromConsole();
            decimal mean = CalculateMean(numbers);
            PrintMean(mean);
        }

        private static decimal[] ReadNumbersFromConsole()
        {
            string userInput = string.Empty;

            Console.WriteLine("How many decimal numbers do you plan to enter?");
            userInput = Console.ReadLine();
            int numbersLength = int.Parse(userInput);

            decimal[] numbers = new decimal[numbersLength];
            for (int i = 0; i < numbersLength; i  )
            {
                Console.WriteLine("Enter a decimal number:");
                userInput = Console.ReadLine();
                decimal number = decimal.Parse(userInput);
                numbers[i] = number;
            }

            return numbers;
        }

        private static decimal CalculateMean(decimal[] numbers)
        {
            // Do your calculations here
            return 0;
        }

        private static void PrintMean(decimal mean)
        {
            // Example display
            Console.WriteLine($"Calculate mean is {mean}");
        }
    }
}
  • Related