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:
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:
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))
{
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.