如何获取此文本文件的最大值? (C#) [英] How do I get the max value of this text file? (C#)

查看:65
本文介绍了如何获取此文本文件的最大值? (C#)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不确定这是否可以提出这样的问题,但我会试一试。

我的作业是编写两个主要部分的代码:一个是创建一个名称和数字的文本文件,另一个是读取相同的文本文件,并打印出文件中最大的数字。这是创建文本文件的代码的一部分(我没有看到任何问题,它工作得很好),类是:

 class Person 
{
public string Name;
公共字符串年龄;
}



主要是:

人a =  Person(); 
Person b = new Person();
Person c = new Person();
a.Name = Abel;
a.Age = 20;
b.Name = Bob;
b.Age = 22;
c.Name = 该隐;
c.Age = 25;
string [] People = {a.Name,a.Age,b.Name,b.Age,c.Name,c.Age};

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



文本文件非常简单,如下所示:

< pre lang =text> Abel
20
Bob
22
Cain
25



此部分工作正常。我遇到麻烦的部分是我应该读取文件并打印最大数字的部分,如下所示:

 字符串 PeopleCheck =  @  C:\ Users \\\\ Desktop\file check\test.txt; 
使用(StreamReader read = new StreamReader(PeopleCheck))
{
while true
{
string FindMax = read.ReadLine();
if (FindMax == null
{
断裂;
}
int test;
if Int32 .TryParse(FindMax, out test))
{
// Console.WriteLine(FindMax); - >这将打印所有数字,每行一个数字
int [] numbers = FindMax.Split(' ')。选择(n = > Convert.ToInt32(n) ).ToArray();
Console.WriteLine( 最高编号为{0},numbers.Max( ));
}
}
}
}



我以为number.Max()会打印出来最大的数字,但输出看起来像这样:

最高数字是20 
最高数字是22
最高数字是25
按任意键继续。 。 。





程序遍历数组中的每个数字,解析每个数字,并将它们作为最大值打印出来。

如果有人能告诉我如何解决这个问题,那么只打印数组的最大值,我将非常感激^^



我尝试了什么:



我尝试将数组放在循环之外,但是数组没有其中的信息,所以我不知道如何解决这个问题。

我也尝试将一个新数组等于'numbers'数组,但它必须在循环中才能获得信息,输出不会改变。

解决方案

您好,



Ur代码需要是改变了一点,因为它没有遵循你想要的逻辑。我只是试图修改你的代码,使其遵循你需要的逻辑。解决方案可以更简化,但我不想这样做,因为它不会解释你究竟缺少什么。







旧代码:

需要修改:

1.需要在循环外取出数组,因为当你找到一个没有数字的数字时它会实例化帮助我们。

2.根据你的文件内容和你试图实现的逻辑,不需要拆分。





使用(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); - >这将打印所有数字,每行一个数字
int [] numbers = FindMax.Split('').Select(n => Convert.ToInt32(n))。ToArray();
Console.WriteLine(最高数字是{0},numbers.Max());
}
}
}
}





修改后的代码:

1.简单来说,我在循环中初始化了列表。

2.在while循环中将文件中存在的所有数字添加到列表中。

3.在while循环逻辑后打印列表中的最大数字。



使用(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(最高数字为{0},numbers.Max());
}


我会将整个结构更改为3个进程。



写文件

而不是每行1个值我会使用逗号作为分隔符每行输出一个人。



阅读文件

然后我会在每行读取并使用拆分将名称和年龄分成一个人对象并添加人物反对集合。



打印单个最大人物对象

然后简单地对集合进行排序并打印第一个人物。


另一种方法是使用 Linq [ ^ ]:



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

正则表达式r =新正则表达式(@\ dd,RegexOptions.ExplicitCapture);
列表< Person>人=行
。其中(l =>!r.Match(l)。成功)
.Zip(行
.Where(l => r.Match(l)。成功),(a,b)=> new Person(){Name = a,Age = Convert.ToInt32(b)})
.ToList();
//返回人员名单

人员最年长=人。其中(p => p.Age == persons.Max(a => a.Age))。SingleOrDefault ();
Console.WriteLine(最老的人是:'{0}',她已经{1}岁。,最古老的人名。姓名,姓名最大的人。年龄);



结果:

年龄最大的人是:'该隐',她今年25岁。





详情请见:

如何:从文本文件中读取(C#编程指南)| Microsoft Docs [ ^ ]

RegexOptions枚举(System.Text.RegularExpressions)| Microsoft Docs [ ^ ]

Regex.Match方法(System.Text.RegularExpressions)| Microsoft Docs [ ^ ]

Enumerable.Zip(IEnumerable< TFirst>,IEnumerable< TSecond>,Func< TFirst,TSecond,TResult>)Method(System.Linq)| Microsoft Docs [ ^ ]


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

解决方案

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());
}


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


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[^]


这篇关于如何获取此文本文件的最大值? (C#)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆