Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.Text;
- using System.Linq;
- class CalcSumAndAverageOfSequence
- {
- // Write a program that reads from the console a sequence of positive integer numbers.
- // The sequence ends when empty line is entered. Calculate and print the sum and average of the elements of the sequence.
- // Keep the sequence in List<int>.
- private static void AddNumber(string inputLine, ref List<int> numsList)
- {
- //asume substring of digits is valid number
- StringBuilder numSB = new StringBuilder();
- for (int i = 0; i < inputLine.Length; i++)
- {
- char currentChar = inputLine[i];
- if (char.IsDigit(currentChar))
- {
- numSB.Append(currentChar);
- }
- else
- {
- if (!string.IsNullOrEmpty(numSB.ToString()))
- {
- numsList.Add(int.Parse(numSB.ToString()));
- numSB = new StringBuilder();
- }
- }
- }
- if (!string.IsNullOrEmpty(numSB.ToString()))
- {
- numsList.Add(int.Parse(numSB.ToString()));
- }
- }
- private static List<int> GetNumbers()
- {
- List<int> numsList = new List<int>();
- string inputLine = "1";
- while (!string.IsNullOrEmpty(inputLine))
- {
- inputLine = Console.ReadLine().Trim();
- AddNumber(inputLine, ref numsList); //solve line: 34, 0FF, 5, $111, kk, !7, 10001011?
- }
- return numsList;
- } //when empty line is entered
- static void Main()
- {
- try
- {
- List<int> numsList = GetNumbers();
- long sum = numsList.Sum();
- double average = numsList.Average();
- Console.WriteLine("sum: {0}\r\naverage: {1}", sum, average);
- }
- catch (ArgumentNullException ane)
- {
- Console.WriteLine(ane.Message);
- }
- catch (OverflowException oe)
- {
- Console.WriteLine(oe.Message);
- }
- catch (InvalidOperationException ioe)
- {
- Console.WriteLine(ioe.Message);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement