I am trying to read from a text file and calculate the total points and average
ID: 3633388 • Letter: I
Question
I am trying to read from a text file and calculate the total points and average points for each classroom.I have it set up the following way:
studentID, roomNumber, testScore
SID001, 1, 91
SID002, 1, 96
SID003, 1, 92
SID004, 2, 90
SID004, 2, 99
SID005, 2, 98
I have this but not sure how to use the classroom list and get the total poinst and average points for each room.
using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Project_2
{
class Program
{
static void Main(string[] args)
{
int ctr;
List<string> lst_strStudents = new List<string>();
List<string> lst_strRooms = new List<string>();
List<int> lst_intGrades = new List<int>();
string[] arr_strData = { };
StreamReader fileIn = new StreamReader(@"C:UsersMichael ContrerasDesktop est.txt");
while (!fileIn.EndOfStream)
{
// split the incoming data into columns
arr_strData = fileIn.ReadLine().Split(", ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
lst_strStudents.Add(arr_strData[0]);
lst_strRooms.Add(arr_strData[1]);
lst_intGrades.Add(int.Parse(arr_strData[2]));
}
}//end main
}
}
Explanation / Answer
using System;
using System.IO;
using System.Collections.Generic;
namespace Project_2
{
public class Program
{
static void Main(string[] args)
{
StreamReader datafile = new StreamReader(@"c:data.txt");
String strData = datafile.ReadToEnd();
datafile.Close();
string FieldSeparator = ",";
String[] lines = strData.Split(Environment.NewLine.ToCharArray(),StringSplitOptions.RemoveEmptyEntries);
List<Student> ListStudents = new List<Student>();
Dictionary<int, int> ListRooms = new Dictionary<int, int>();
foreach (string item in lines)
{
String[] fields = item.Split(FieldSeparator.ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
ListStudents.Add(new Student(fields[0], Int32.Parse(fields[1]), Int32.Parse(fields[2])));
if (!ListRooms.ContainsKey(Int32.Parse(fields[1])))
{
ListRooms.Add(Int32.Parse(fields[1]), Int32.Parse(fields[1]));
}
}
int TotalPoints = 0;
double AvgPoints = 0;
int nCount = 0;
foreach (var room in ListRooms)
{
int roomid = room.Value;
foreach (var student in ListStudents)
{
if (student.roomNumber == roomid)
{
nCount++;
TotalPoints = TotalPoints + student.testScore;
}
}
Console.WriteLine(" Room #"+roomid+" : Total Points = "+TotalPoints +
", Average Points = " + (TotalPoints/nCount));
nCount = 0;
TotalPoints = 0;
}
Console.Read();
}
}
class Student
{
public String studentID;
public int roomNumber;
public int testScore;
public Student(String stid, int rmid, int ts)
{
studentID = stid;
roomNumber = rmid;
testScore = ts;
}
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.