0

I had done a previous exercise whereby I had to write a program where a user would input 30 different numbers (hours) and the program would spit out the array, average, min, and max. That was fine. Now, however, I am tasked with reading the numbers from a text file (and outputting the same as before - array, avg, min, max).

I am hitting an error based on the original exercise, where I am told that a name does not exist in the program (I understand this is because the text doc now holds that previous name). I don't know what I need to do to change this.

I've watched some videos and found similar problems listed on this site but am stuck :(. Can anyone help?

Program code is:

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

namespace IntsArray
{
    class Program
    {
        static void Main(string[] args)
        {

            StreamReader myReader = new StreamReader("Values.txt");
            string line = "";

            while (line != null)
            {
                line = myReader.ReadLine();
                if (line != null)
                    Console.WriteLine(line);
            }
            myReader.Close();
            Console.ReadLine();

            for (int index = 0; index < hoursArray.Length; index++)
            {
                Console.Write("Enter your hours: ");
                hoursArray[index] = int.Parse(Console.ReadLine());
            }
            Console.WriteLine("Numbers in the list: " + hoursArray.Length);
            for (int index = 0; index < hoursArray.Length; index++)
            {
                Console.WriteLine(hoursArray[index]);
            }
            Console.ReadKey();

            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 = " + average.ToString("N2"));


            int high = hoursArray[0]; 

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

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


            int low = hoursArray[0];   

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

            Console.WriteLine("Lowest number = " + low);
            Console.ReadKey();

        }
    }
}

The numbers in the Values.txt looks like this:

8
24
9
7
6
12
10
11
23
1
2
9
8
8
9
7
9
15
6
1
7
6
12
10
11
23
1
2
9
8

I understand the problem, I just do not know how to fix it!

10
  • 1
    What is the exact error that you're seeing?.. Commented Jun 17, 2016 at 7:10
  • 1
    What is hoursArray, where is it declared? Commented Jun 17, 2016 at 7:11
  • it's long time ago, since I used this... but while (line != null), I think it should be while(!myReader.eof()) but I'm not sure Commented Jun 17, 2016 at 7:12
  • There was a similar question just minutes ago: stackoverflow.com/questions/36616958/… Commented Jun 17, 2016 at 7:12
  • @Thomas this is the specific thing you mean while ((line = sr.ReadLine()) != null) Commented Jun 17, 2016 at 7:17

3 Answers 3

3

If you want to read numbers from a file, why do you have this code ?

for (int index = 0; index < hoursArray.Length; index++)
{
    Console.Write("Enter your hours: ");
    hoursArray[index] = int.Parse(Console.ReadLine());
}

what you can do is read the numbers from a file, store it in Array or List and then use Linq to get Max, Min and Average.

List<int> Numbers = System.IO.File.ReadAllLines("Your File Path")
                   .Select(N=> Convert.ToInt32(N)).ToList();

Console.WriteLine(Numbers.Average());
Console.WriteLine(Numbers.Max());
Console.WriteLine(Numbers.Min());
Sign up to request clarification or add additional context in comments.

5 Comments

The answer to the first question is because it was editing an old file and updating it to read from text, previously it was a user-input program. I guess I just missed removing that first part. So on to your next point - as I stated I currently have all of the numbers linked to a text file - how do I need to alter the text file as well as the program to read both?
I don't get it, why and when do you need to alter your text file?
Mate, I don't have a clue, that's why I'm here asking! What you said was "what you can do is read the numbers from a file, store it in Array or List and then use Linq to get Max, Min and Average.", and I'm trying to ask what do I do to my file for this to be possible?
what you have to do to your file in NOTHING! just create a text file, and type the value in it as you said in your question
In that case, haven't I already done that? I listed in the initial question the contents of the text file.
0

First thing you will do is to identify the number of lines in the textfile.

var file = new StreamReader("file.txt").ReadToEnd(); 
var lines = file.Split(new char[] {'\n'});  
var count = lines.Count;

Based on this count initialize your array

int[] hoursArray = new int[count];

After that populate your array.

int index = 0;
while ((line = sr.ReadLine()) != null) 
{
    hoursArray[index++] = Convert.ToInt32(line);
}

Then last step, you can now apply linq to get max min and avg same as what arvin said.

var max = hoursArray.Max();
var min = hoursArray.Min();
var avg = hoursArray.Avg();

4 Comments

Thanks Katana! Is there any chance that you could maybe add those in to my program code so I can see what the code should look like from start to finish? If that's not too much trouble of course.
@LegendIsReal much better if you will be the one to integrate it, that's the way you learn by trying. Just notify us if you have issues. The steps are already in order, you can do it :)
Good point :). I just tried to make some edits based on one of the lower suggestions, and I had it output the array, but then it no longer gives me the max min and average, just 0's. Looking at your suggestions, I am unfamiliar with a lot of the wording so not too sure what to change things from. I can't copy paste the whole code here to show you :S
@LegendIsReal just update your post, so I can picture it, cant tell whats wrong
0

You need to define the array

int[] hoursArray = new int[WHATEVER LENGTH IT SHOULD BE];

then your StreamReader read line thing has to look something like this:

string line = "";
int position = 0; //needed to set the array position
while (line != null)
{
    line = myReader.ReadLine();
    if (line != null)
    {
        Console.WriteLine(line);
        hoursArray[position] = int.Parse(line); //convert line to int and sotres it in the array
        position++;
    }
}

if you want to make it more flexible i would use a list instead of an array

Edit: min max avg calulation:

int max = 0;
int min = 9999999;
double avg = 0;

for (int i = 0; i < hoursArray.Length; i++)
{
    if (hoursArray[i] > max) //if there is a higher value then the current max
        max = hoursArray[i];

    if (hoursArray[i] < min) //if there is a lower value then the current min
        min = hoursArray[i];

    avg = avg + hoursArray[i];
}
avg = avg / hoursArray.Length;

Console.WriteLine("Max: " + max);
Console.WriteLine("Min: " + min);
Console.WriteLine("Avg: " + avg);
Console.ReadLine();

You just need to put them together in you main and there you have it enter image description here

7 Comments

Thanks for that, I will give that a shot shortly. Where you say WHATEVER LENGTH IT SHOULD BE, is that simply just the number of inputs from the text doc I have? in this case, 30?
Yes it just defines the length of the array in your case it should be 30
Hi Jan, where abouts do I include the int[] hoursArray = new int[WHATEVER LENGTH IT SHOULD BE];?
You can it is before StreamReader myReader =... Basically you have to define it before you can use it in the while loop
btw you also should remove the first for loop for entering numbers or they will override the values form the text file
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.