Kinjal Maru Shah Kinjal Maru Shah - 23 days ago 9
C# Question

Average of List from input file

I have an input file where I have primary scores and secondary scores. I need to find the average of the primary scores.

I am able to read the primary and secondary score and add them into Lists. But while calculating average, I am getting an error on the line s1.Average(PrimaryScore);

I am attaching the program.cs and regression .cs classes. Thank you for any help.

class Program
{
static Regression s1;
static void Main(string[] args)
{
int numRecords = 0;
List<double> PrimaryScore = new List<double>();
List<double> SecondaryScore = new List<double>();
FileStream fs = null;
Console.Write("Enter the file path: ");

while (fs == null)
{
string fileName = Console.ReadLine();
fs = OpenFileForRead(fileName);
}

StreamReader sr = new StreamReader(fs);
ReadFirstValueAsInt(sr, ref numRecords);
sr.ReadLine();
for (int i = 1; i <= numRecords; i++)
{
ReadRecordAsDoubleList(sr, PrimaryScore);
ReadRecordAsDoubleList(sr, SecondaryScore);

Console.WriteLine("Primary Data set {0}: ", i);
foreach (double d in PrimaryScore)
Console.Write(d + " ");

Console.WriteLine();
Console.ReadLine();
PrimaryScore.Clear();
sr.ReadLine();
Console.WriteLine("Secondary Data set {0}: ", i);
foreach (double d in SecondaryScore)
Console.Write(d + " ");

Console.WriteLine();
Console.ReadLine();
SecondaryScore.Clear();
}
s1 = new Regression();
s1.Average(PrimaryScore); //getting an error here
}

public static FileStream OpenFileForRead(string fileName)
{
try
{
return new FileStream(fileName, FileMode.Open, FileAccess.Read);
}
catch (Exception e)
{
Console.Write("Problem opening file {0}, please enter a valid path: ", fileName);
}

return null;
}

public static void ReadFirstValueAsInt(StreamReader sr, ref int numRecords)
{
try
{
numRecords = Int32.Parse(sr.ReadLine());

}
catch (Exception e)
{
Console.Write(e.Message);
}
}

public static void ReadRecordAsDoubleList(StreamReader sr, List<double> cr)
{
try
{
string[] doubles = sr.ReadLine().Split(new char[] { ' ' });

foreach (string s in doubles)
cr.Add(Double.Parse(s));

}
catch (Exception e)
{
Console.Write(e.Message);
}
}
}


Regression Class which is called from the program Class

class Regression
{

public static double Average(List<double> PrimaryScore)
{
int sum = 0;

foreach (int element in PrimaryScore)
sum += element;

return (double)sum / PrimaryScore.Count;
}
}

Answer

Average is declared as a static method, so you eithr call it using Regression.Average(PrimaryScore) or, you remove the static modifier from the method definition so you could keep calling it using s1.Average(PrimaryScore).

such as your method defintion becomes like this :

 public static double Average(List PrimaryScore)
 {
    .
    .
    .