简体   繁体   中英

c# read text file find min max average

I am studying at TAFE but the class and myself are getting no help from my lecturer at all.

I need to read from a txt file and find the min max and average from it and print it to the console.

The previous exercise was to get min max average from an array and I have written this and it works fine. I am using VS2012.

I have written the code to read the text file and print it to the console - but i cannot find the min max and average. I get "Object reference not set to an instance of an object." when i run the program.

Note that I have used the same code to find min max average as from an array... I feel this might be the issue but I cannot work it out!!

Here is my code for the array...

        static void Main(string[] args)
        {
            int[] hoursArray = { 1, 24, 9, 7, 6, 12, 10, 11, 23, 8, 2, 9, 8, 8, 9, 7, 9, 15, 6, 1, 7, 6, 12, 10, 11, 23, 1, 2, 9, 8 };
            for (int i = 0; i < hoursArray.Length; i++)
            {
                Console.WriteLine(hoursArray[i].ToString());
            }

            {

                {
                    int low = hoursArray[0];
                    for (int index = 1; index > hoursArray.Length; index++)
                    {
                        if (hoursArray[index] < low)
                        {
                            low = hoursArray[index];
                        }
                    }

                    Console.WriteLine("Lowest Hours Parked = " + low);

                int high = hoursArray[0];
                for (int index = 1; index < hoursArray.Length; index++)
                {
                    if (hoursArray[index] > high)
                    {
                        high = hoursArray[index];
                    }
                }

                Console.WriteLine("Highest Hours Parked = " + high);

                    int total = 0;
                    double average = 0;
                    for (int index = 0; index < hoursArray.Length; index++)
                    {
                        total = total + hoursArray[index];
                    }

                    average = (double)total / hoursArray.Length;
                    Console.WriteLine("Average Hours Parked =" + average.ToString("N"));

                    Console.ReadLine();
                }
            }
        }
    }
}

As mentioned this works fine. Now for my problem... I have written the code to display the data from the text file as per below with my comments...

        static void Main(string[] args)
    {
        StreamReader hours = new StreamReader("hours.txt");
        string number = "";

        while (number != null)
        {
            number = hours.ReadLine();
            if (number != null)
                Console.WriteLine(number);
        }
        //list of numbers above is all ok when running program

        int total = 0;
        double average = 0;
        for (int index = 0; index < number.Length; index++)
        {
            total = total + number[index];
        }
        average = (double)total / number.Length;
        Console.WriteLine("Average = " + average.ToString("N2"));

        int high = number[0];

        for (int index = 0; index < number.Length; index++)
        {
            if (number[index] > high)
            {
                high = number[index];
            }
        }

        Console.WriteLine("Highest number = " + high);

        int low = number[0];

        for (int index = 0; index > number.Length; index++)
        {
            if (number[index] < low)
            {
                low = number[index];
            }
        }
        Console.WriteLine("Lowest number = " + low);
        hours.Close();
                Console.ReadLine();
        }
    }
}

I suggest using Linq :

// First of all define the source - it can be an array, file - whatever:
// var source = hoursArray; // e.g. source for the array
var source = File
  .ReadLines(@"C:\MyFile.txt")         //TODO: put actual file here
  .SelectMany(line => line.Split(',')) //TODO: put actual separator here
  .Select(item => int.Parse(item));

// having got source (IEnumerable<int>) let's compute min, max, average

int max = 0;
int min = 0;
double sum = 0.0; // to prevent integer division: 7/2 = 3 when 7.0 / 2 = 3.5
int count = 0;
boolean firstItem = true;

foreach (item in source) {
  sum += item; 
  count += 1;

  if (firstItem) {
    firstItem = false;
    max = item;
    min = item;
  } 
  else if (item > max)
    max = item;
  else if (item < min)
    min = item;
}

// Finally, formatted output
Console.Write("Min = {0}; Max = {1}; Average = {2}", min, max, sum / count);

Use File.ReadLines to read the file contents and then convert those to int array using simple Linq statements.

int[] hoursArray = File
  .ReadLines("filepath")  // Read all lines,
  .SelectMany(s => s.Split(",").Select(int.Parse)) // Split by ',' and convert them to int.
  .ToArray(); 

Once you do this, rest of the code should work as it is.

Also one more suggestion, there are predefined methods/functions on array to get Average , Min and Max .

You could just do.

var avg = hoursArray.Average();
var min = hoursArray.Min();
var max = hoursArray.Max();
string text = System.IO.File.ReadAllText("filePath");
        int[] hoursArray = (text.Split(' ').ToArray()).Select(x => Convert.ToInt32(x)).ToArray();
        int max = hoursArray.Max();
        int min = hoursArray.Min();
        double avg = hoursArray.Average();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM