-8

Refer to this answer: Pass multiple optional parameters to a C# function Question about Params (to a point). What I want to know is, how (if possible) can this be used to take user input rather than predefined numbers? So, I understand that I can do Console.Write(calculator.Add(1, 43, 23)) but would like to deal with user input.

class Program
{
    static void Main(string[] args)
    {
        var calculator = new Calculator();
        var input = Convert.ToInt32(Console.ReadLine());

        Console.WriteLine(calculator.Add(input));
    }
}

public class Calculator
{
    public int Add(params int[] numbers)
    {
        var sum = 0;
        foreach (var number in numbers)
        {
            sum += number;
        }
        return sum;
    }
}
wilfy
  • 17
  • 1
  • 6

2 Answers2

0

You can store all the user inputs in an array and pass the array to Add.

var calculator = new Calculator();
var input = Array.ConvertAll<int>(Console.ReadLine().Split(' '));
calculator.Add(input);
AustinWBryan
  • 3,249
  • 3
  • 24
  • 42
Test12345
  • 1,625
  • 1
  • 12
  • 21
-2

Something along these lines should work. I might have made syntax errors :D

using System;
class Program
{
    static void Main(string[] args)
    {
        var calculator = new Calculator();
        var input = GetNumbers();
        calculator.Add(input);
        Console.WriteLine(calculator.Add(input));
    }

    public static int[] GetNumbers()
    {
      Console.WriteLine("Enter Numbers Seperated With a Space");
      string input = Console.ReadLine(); //Get user input with this
      string[] arr = input.Split(' '); //Split the input at spaces
      int[] output = new int[arr.Length]; //create in array of same length

      for(int i = 0; i < output.Length; i++)
      {
          output[i] = Int32.Parse(arr[i]); //parse every value and add to int array
      }
      return output;
    }
}

public class Calculator
{
    public int Add(params int[] numbers)
    {
        var sum = 0;
        foreach (var number in numbers)
        {
            sum += number;
        }
        return sum;
    }
}
Eddie D
  • 1,120
  • 7
  • 16
  • Thanks, I'll look at this. Any idea why my question has been downvoted? I don't understand, its a legitimate question. This site does dismay me sometimes. What is its point if not for people like me to come and learn from it, and gain others knowledge. – wilfy Jun 02 '18 at 22:21
  • Just to say that in this as well as the OP, there's an unnecessary line of `calculator.Add(input);` before the `Console.WriteLine(calculator.Add(input));`. OP may be interested in putting in a variable where the result is to be re-used. – MacroMarc Jun 02 '18 at 23:03
  • Macro, yes I should have edited the code a little before posting. I left that line in as was because I was in the middle of changes. I'll edit. – wilfy Jun 03 '18 at 10:11