user10602246
user10602246

Reputation:

Printing max value in a file

Each line in the file has a name with the numbers following the name that represents how popular that name was to that specific year starting at 1970

Addison 779 759 895 0 0 0 0 0 794 585 323

So 779 is how popular the name was in 1970, 759 is the year 1971... 323 is the year 1980.

What I am trying to find is the year the name was most popular and print out the name and year in the file that has the max array value. So the output in the file will look like

Addison 1978

This is the code I have so far

    TextReader file = new StreamReader("Files\\Excerise_Files\\SSA_Names_Short_Find_Max.txt");
        StreamWriter output = new StreamWriter("Files\\SSA_Names_Max.txt");
        char[] delimiters = { ' ', '\t' };

        string nameLine;
        while ((nameLine = file.ReadLine()) != null)
        {
            string[] tokensfromLine = nameLine.Split(delimiters, StringSplitOptions.RemoveEmptyEntries);
            int max = 0;
            int num = 0;
            for(int i = 1; i < tokensfromLine.Length; i++)
            {
                if(Int32.TryParse(tokensfromLine[i], out num))
                {
                    if( num > max)
                    {
                        max = num;
                    }
                }              

            }
    output.Dispose();

I don't know how to print out the year that represents the max value? I was trying to figure out how to change the index of the array to display the years. I don't know how to do that. I am new to coding and don't know so much, but I would like to know how to print out the index in the array. Also this is c# forgot to mention that. Thank you!

Upvotes: 0

Views: 68

Answers (1)

nemanja228
nemanja228

Reputation: 551

I assumed that it's a C# console application.

The code has been split into several smaller functions with meaningful names and all have been parametrized so you can use them with different file names and years.

The solution I provided you has a lot of small C# details that you will probably want to understand:

I advise you to carefully analyze the example to gain as much knowledge as possible.

You can find the whole code here:.

Upvotes: 0

Related Questions