Click here to Skip to main content
15,889,403 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I'm not sure if this is the place to ask questions like that, but I'll give it a shot.
My homework is to write a code of two major parts: one is to create a text file of names and numbers, and the other one is to read the same text file, and print out the biggest number out of the file. This is the part of the code that creates the text file (that I don't see any problems with, it works just fine), the class is:
class Person
{
    public string Name;
    public string Age;
}

The main is:
C#
Person a = new Person();
     Person b = new Person();
     Person c = new Person();
     a.Name = "Abel";
     a.Age = "20";
     b.Name = "Bob";
     b.Age = "22";
     c.Name = "Cain";
     c.Age = "25";
     string[] People = { a.Name, a.Age, b.Name, b.Age, c.Name, c.Age };

     using (StreamWriter write = new StreamWriter(@"C:\Users\A\Desktop\file check\test.txt"))
     {
         for (int i = 0; i < People.Length; i++)
         {
             write.WriteLine(People[i]);
         }
     }

The text file is very simple, and looks like this:
Abel
20
Bob
22
Cain
25

This part works ok. The part I'm having trouble with is the part where I'm supposed to read the file and print the biggest number, which looks like this:
C#
string PeopleCheck = @"C:\Users\A\Desktop\file check\test.txt";
      using (StreamReader read = new StreamReader(PeopleCheck))
      {
          while (true)
          {
              string FindMax = read.ReadLine();
              if (FindMax == null)
              {
                  break;
              }
              int test;
              if(Int32.TryParse(FindMax, out test))
              {
                 // Console.WriteLine(FindMax); --> this will print all numbers, one number in each line
                  int[] numbers = FindMax.Split(' ').Select(n => Convert.ToInt32(n)).ToArray();
                  Console.WriteLine("the highest number is {0}", numbers.Max());
              }
          }
      }
  }

I thought that numbers.Max() will print out the biggest number, but the output looks like this:
the highest number is 20
the highest number is 22
the highest number is 25
Press any key to continue . . .


The program goes through every number in the array, parses each of them, and prints them out as the max value.
If anyone can show me how to fix this, so only the max value of the array is printed, I'll be very grateful ^^

What I have tried:

I tried putting the array outside of the loop, but then the array doesn't have the information in it, so I'm not sure how to fix this.
I also tried putting a new array the equals to the 'numbers' array, but it has to be in the loop to get the info, and the output doesn't change.
Posted
Updated 20-Sep-18 3:56am

Hello,

Ur code needs to be changed a bit as it is not following the logic u want. I am just trying to modify ur code in such a way that it follows the logic u need. Solution can be more simplified but I don't want to do as it wont explain what you are missing exactly.



Old Code:
modification required:
1. Need to take out array outside while loop as it will instantiate when ever u find a number which doesn't help us.
2. There is no need of split as per ur file content and the logic u r trying to implement.


    using (StreamReader read = new StreamReader(PeopleCheck))
    {
        while (true)
        {
            string FindMax = read.ReadLine();
            if (FindMax == null)
            {
                break;
            }
            int test;
            if(Int32.TryParse(FindMax, out test))
            {
               // Console.WriteLine(FindMax); --> this will print all numbers, one number in each line
                int[] numbers = FindMax.Split(' ').Select(n => Convert.ToInt32(n)).ToArray();
                Console.WriteLine("the highest number is {0}", numbers.Max());
            }
        }
    }
}


Modified Code:
1. In simple terms, I have initialized list outside while loop.
2. Added all numbers present in file to the list in while loop.
3. Printed the max number present in list after while loop logic.

using (StreamReader read = new StreamReader(PeopleCheck))
{
    List<int> numbers = new List<int>();

    while (true)
    {
        string FindMax = read.ReadLine();
        if (FindMax == null)
        {
            break;
        }

        int test;
        if (Int32.TryParse(FindMax, out test))
        {
            numbers.Add(test);
        }
    }

    Console.WriteLine("the highest number is {0}", numbers.Max());
}
 
Share this answer
 
I would change the entire structure into 3 processes.

Write the file
Instead of 1 value per line I would output a person per line using a comma as a delimiter.

Read the file
Then I would read in each line and use split to separate the name and age back into a person object and add the person object to a collection.

Print the single max person object
Then simply sort the collection descending and print the first person.age
 
Share this answer
 
Another way is to use Linq[^]:

string[] lines = File.ReadAllLines(@"fullfilename.txt");

Regex r = new Regex(@"\d", RegexOptions.ExplicitCapture);
List<Person> persons = lines
    .Where(l=>!r.Match(l).Success)
    .Zip(lines
        .Where(l=>r.Match(l).Success), (a, b) => new Person(){Name=a, Age=Convert.ToInt32(b)})
    .ToList();
//retuns the list of persons

Person oldestperson =  persons.Where(p=>p.Age==persons.Max(a=>a.Age)).SingleOrDefault();
Console.WriteLine("The oldest person is: '{0}', she's {1} years old." ,oldestperson.Name, oldestperson.Age);

Result:
The oldest person is: 'Cain', she's 25 years old.


For further details, please see:
How to: Read From a Text File (C# Programming Guide) | Microsoft Docs[^]
RegexOptions Enum (System.Text.RegularExpressions) | Microsoft Docs[^]
Regex.Match Method (System.Text.RegularExpressions) | Microsoft Docs[^]
Enumerable.Zip(IEnumerable<TFirst>, IEnumerable<TSecond>, Func<TFirst,TSecond,TResult>) Method (System.Linq) | Microsoft Docs[^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900