Advertisement
pshipkovenski

CalcSumAndAverageOfSequence

Jul 13th, 2013
58
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.22 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4. using System.Linq;
  5.  
  6. class CalcSumAndAverageOfSequence
  7. {
  8.     // Write a program that reads from the console a sequence of positive integer numbers.
  9.     // The sequence ends when empty line is entered. Calculate and print the sum and average of the elements of the sequence.
  10.     // Keep the sequence in List<int>.
  11.  
  12.     private static void AddNumber(string inputLine, ref List<int> numsList)
  13.     {
  14.         //asume substring of digits is valid number
  15.  
  16.         StringBuilder numSB = new StringBuilder();
  17.  
  18.         for (int i = 0; i < inputLine.Length; i++)
  19.         {
  20.             char currentChar = inputLine[i];
  21.  
  22.             if (char.IsDigit(currentChar))
  23.             {
  24.                 numSB.Append(currentChar);
  25.             }
  26.             else
  27.             {
  28.                 if (!string.IsNullOrEmpty(numSB.ToString()))
  29.                 {
  30.                     numsList.Add(int.Parse(numSB.ToString()));
  31.                     numSB = new StringBuilder();
  32.                 }
  33.             }
  34.         }
  35.  
  36.         if (!string.IsNullOrEmpty(numSB.ToString()))
  37.         {
  38.             numsList.Add(int.Parse(numSB.ToString()));
  39.         }
  40.  
  41.     }
  42.  
  43.     private static List<int> GetNumbers()
  44.     {
  45.         List<int> numsList = new List<int>();
  46.  
  47.         string inputLine = "1";
  48.  
  49.         while (!string.IsNullOrEmpty(inputLine))
  50.         {
  51.             inputLine = Console.ReadLine().Trim();
  52.             AddNumber(inputLine, ref numsList); //solve line: 34, 0FF, 5, $111, kk, !7, 10001011?
  53.         }
  54.  
  55.         return numsList;
  56.     } //when empty line is entered
  57.  
  58.     static void Main()
  59.     {
  60.         try
  61.         {
  62.             List<int> numsList = GetNumbers();
  63.  
  64.             long sum = numsList.Sum();
  65.  
  66.             double average = numsList.Average();
  67.  
  68.             Console.WriteLine("sum: {0}\r\naverage: {1}", sum, average);
  69.         }
  70.         catch (ArgumentNullException ane)
  71.         {
  72.             Console.WriteLine(ane.Message);
  73.         }
  74.         catch (OverflowException oe)
  75.         {
  76.             Console.WriteLine(oe.Message);
  77.         }
  78.         catch (InvalidOperationException ioe)
  79.         {
  80.             Console.WriteLine(ioe.Message);
  81.         }
  82.     }
  83. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement