6 Replies - 1182 Views - Last Post: 14 November 2011 - 01:48 PM Rate Topic: -----

#1 notSo smartGuy  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 18
  • Joined: 09-February 11

File reading - addition and average

Posted 02 March 2011 - 03:44 PM

Hello. I am kinda stuck atm. I never done anything mathematical in c# and curious how I would go about doing so. I am want to get the sum and average of every three numbers in a .txt file(attached).

I have this so far:

using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            string[] fields;
            const char DELIM = ',';
            string inputRecord;
            string FILENAME = @"C:\Documents and Settings\Owner\Desktop\test.txt";
            string ID = "";
            int salary = 0;

            FileStream inFile = new FileStream(FILENAME, FileMode.Open, FileAccess.Read);
            StreamReader reader = new StreamReader(inFile);

            inputRecord = reader.ReadLine();
            while (inputRecord != null)
            {
                fields = inputRecord.Split(DELIM);
                ID = fields[0];
                if(ID.Trim().Length > 0 && int.TryParse(fields[1], out salary))
                {
                    //Process records
                    Console.Write("{0} ", ID);
                    Console.Write("Classroom number{0} ", fields[1]);
                    Console.WriteLine("Test score{0}", fields[2]);
                   
                }
                else //skip record
                    Console.WriteLine("Error, skipping record");
                    inputRecord = reader.ReadLine();

                   
            }
        }// end main
    }
}




Was thinking about adding:
for(ID = 0; ID < 85; ID + 3)
           Console.WriteLine("The total points for this classroom is {0}");
           Console.WriteLine("The average points for this classroom is {0}");


in the while loop but I dont think that is correct at all. Plus not sure where or how to do the math.

Attached File(s)

  • Attached File  test.zip (547bytes)
    Number of downloads: 87

This post has been edited by notSo smartGuy: 02 March 2011 - 03:47 PM


Is This A Good Question/Topic? 0
  • +

Replies To: File reading - addition and average

#2 Curtis Rutland  Icon User is offline

  • (╯□)╯︵ (~ .o.)~
  • member icon


Reputation: 5101
  • View blog
  • Posts: 9,283
  • Joined: 08-June 10

Re: File reading - addition and average

Posted 02 March 2011 - 03:52 PM

Alright, you've already got a big glaring problem. Streams have to be closed if they're opened.

Streams (and many other objects) can be created in a using statement, which will automatically dispose of them when you're done:

using(StreamReader reader = new StreamReader(FILENAME)){
  //do reading in here.
};


Next, I would suggest using a data structure to simplify looping through it. Create a class that holds your three integers. Then you can just loop through the array, starting at 0 and iterating by i += 3 each time, and just assign the ints to a new instance of the class.

Then just do the math with methods in the class. Make a method that does the average.
Was This Post Helpful? 0
  • +
  • -

#3 Sergio Tapia  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 1258
  • View blog
  • Posts: 4,168
  • Joined: 27-January 10

Re: File reading - addition and average

Posted 02 March 2011 - 03:56 PM

Woah woah woah compadre. Time for some Clean Code 101. Split this baby up into logical functions and suddenly that gargantuan problem is no longer confusing to read and easier to maintain.

public double GetSumOfNumbers(List<double> numbers)
{
    //Do your salsa here.
}

public double GetAverageOfNumbers(List<double> numbers)
{
    //Make your guacamole here.
}

public List<double> GetEveryThreeValues(string source)
{
    //Fetch every three items here.
}

public string GetFileContents(string filePath)
{
    //Magic here.
}



So now we have four small, easy to understand methods that do what we want. Which one do you need help with? I'm sure you can even solve this yourself now. That's the power of creating small methods.

This post has been edited by Sergio Tapia: 02 March 2011 - 03:57 PM

Was This Post Helpful? 2
  • +
  • -

#4 notSo smartGuy  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 18
  • Joined: 09-February 11

Re: File reading - addition and average

Posted 02 March 2011 - 08:00 PM

View PostSergio Tapia, on 02 March 2011 - 03:56 PM, said:

Woah woah woah compadre. Time for some Clean Code 101. Split this baby up into logical functions and suddenly that gargantuan problem is no longer confusing to read and easier to maintain.

public double GetSumOfNumbers(List<double> numbers)
{
    //Do your salsa here.
}

public double GetAverageOfNumbers(List<double> numbers)
{
    //Make your guacamole here.
}

public List<double> GetEveryThreeValues(string source)
{
    //Fetch every three items here.
}

public string GetFileContents(string filePath)
{
    //Magic here.
}



So now we have four small, easy to understand methods that do what we want. Which one do you need help with? I'm sure you can even solve this yourself now. That's the power of creating small methods.


I am trying to get the sum and average for each classroom. The way my test file is set up is. Student ID, room#, test score.

From the looks of your code I would have to read from file for every method, no?
Was This Post Helpful? 0
  • +
  • -

#5 Curtis Rutland  Icon User is offline

  • (╯□)╯︵ (~ .o.)~
  • member icon


Reputation: 5101
  • View blog
  • Posts: 9,283
  • Joined: 08-June 10

Re: File reading - addition and average

Posted 02 March 2011 - 08:14 PM

Absolutely not. You read once, store the numbers in a List<double> (or List<int>, if the numbers are integers), then do your work on them.
Was This Post Helpful? 0
  • +
  • -

#6 Sergio Tapia  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 1258
  • View blog
  • Posts: 4,168
  • Joined: 27-January 10

Re: File reading - addition and average

Posted 02 March 2011 - 09:30 PM

View PostnotSo smartGuy, on 02 March 2011 - 11:00 PM, said:

I am trying to get the sum and average for each classroom. The way my test file is set up is. Student ID, room#, test score.

From the looks of your code I would have to read from file for every method, no?


Not if you declare a string variable at the class scope.

private string _contentsOfFile;

public void LoadContentFromFile(string filePath)
{
    _contentsOfFile = //read the file contents here.
}



Only read it once and you can use anywhere in your class. Divide and conquer my friend!

Let's pause for a bit and focus on a single aspect of your problem. First try to just read the contents of a file, and save it to the string variable _contentsOfFile. Then we can check that off the list and get closer to the ultimate goal of the application.

This post has been edited by Sergio Tapia: 02 March 2011 - 09:32 PM

Was This Post Helpful? 0
  • +
  • -

#7 notSo smartGuy  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 18
  • Joined: 09-February 11

Re: File reading - addition and average

Posted 14 November 2011 - 01:48 PM

I know this thread is few months old but I came across this and was curious. I have this set up so far....

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:\Users\Michael Contreras\Desktop\test.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

    }
}




My test file is set up with only 3 students per room with 30 rooms(see op). How would I loop through each room and get the total and average points for each room. Im lost at this point..

This post has been edited by notSo smartGuy: 14 November 2011 - 01:50 PM

Was This Post Helpful? 0
  • +
  • -

Page 1 of 1