简体   繁体   English

C#-从文本文件构建数组

[英]C# - Building an Array from Text File

I am attempting to build an array of batting averages from a .txt file, but most of the resources I am finding online to assist in how to work this out either work with text in the following format: 我正在尝试从.txt文件构建一系列击球平均值,但是我在网上找到的大部分资源都可以帮助解决该问题,或者使用以下格式的文本:

1 2 3 4 5 1 2 3 4 5

2 3 4 5 6 2 3 4 5 6

etc. 等等

... or in the following format: ...或以下格式:

1, 2 一二

3, 4 3 4

etc. 等等

Unfortunately, my text file is in the following format, and changing the format is not an option. 不幸的是,我的文本文件采用以下格式,因此不能更改格式。 Each odd line number denotes a player, with the following even line number being their average at bat in that instance (just information for context): 每个奇数号表示一个玩家,以下偶数号是该情况下其在蝙蝠上的平均值(仅用于上下文的信息):

1 1

2 2

3 3

4 4

Using this file, I want to assign the odd numbers to the index of the array, and then populate the even numbers as values, calculating them as I go. 使用此文件,我想将奇数分配给数组的索引,然后将偶数填充为值,并在进行操作时对其进行计算。 I believe that I can parse out how to accomplish the calculations, I just cannot ascertain how to grab the data nor associate the odd numbers with array indexes. 我相信我可以解析出如何完成计算,只是无法确定如何获取数据,也无法将奇数与数组索引相关联。

Code as follows. 代码如下。 File is to be specified by user: 文件由用户指定:

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

static string FileName()
    {
        string doc = Console.ReadLine();
        return doc;
    }

static void Main(string[] args)
    {

        try
        {

            Console.Write("Where is the data file for batting averages located? ");
            string doc = FileName();
            StreamReader reader = new StreamReader(doc);
            string avg = reader.ReadToEnd();
            reader.Close();

        }
        catch (System.IO.FileNotFoundException) 
        {
            Console.WriteLine("The file can not be found.");
        }
        catch (System.FormatException)
        {
            Console.WriteLine("Invalid file.");
        }
        catch (System.ArgumentException)
        {
            Console.WriteLine("Enter a valid file name.");
        }
        catch (System.Exception exc)
        {
            Console.WriteLine(exc.Message);
        }
    }

Any assistance would be welcome. 欢迎任何帮助。 Please keep in mind I am a student and still learning the earliest parts of C#, so any truly advanced techniques are probably going to be lost on me. 请记住,我是一名学生,仍在学习C#的最早部分,因此任何真正先进的技术都可能会丢失给我。

You can read the Text file Line by line (or use System.IO.File.ReadAllLines - to get a string[] - Link ). 您可以逐行读取文本文件(或使用System.IO.File.ReadAllLines-获取字符串[] -Link )。 Now Odd/Even indices can be read and processed per your wish. 现在,您可以按照自己的意愿读取和处理奇/偶索引。

Tip: Your text file format is basic and error prone. 提示:您的文本文件格式是基本格式,容易出错。

You can do something like this: 您可以执行以下操作:

var lines = File.ReadAllLines(FileName());
for (int i = 0; i < lines.Length; i += 2)
{
    Console.WriteLine($"Player Name: {lines[i]}");
    Console.WriteLine($"Player Average: {lines[i + 1]}");
}

After working late into the night yesterday, I came up with code that resolved my issue: 在昨天工作到深夜之后,我想出了解决我的问题的代码:

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

class Program
{
    static void Main(string[] args)
    {
        Console.Write("Where is the data file for batting averages located? ");
        string doc = Console.ReadLine();

        int[] avg = new int[9];
        int val1=0, val2=0, val3=0, val4=0, val5=0, val6=0, val7=0, val8=0, val9=0;
        int cnt1=0, cnt2=0, cnt3=0, cnt4=0, cnt5=0, cnt6=0, cnt7=0, cnt8=0, cnt9=0;

        try
        {
            StreamReader reader = new StreamReader(doc);
            var lines = File.ReadAllLines(doc);
            int[] index = Array.ConvertAll(lines, int.Parse);
            //Console.WriteLine(lines); //displays contents of text file
            reader.Close();

            for (int i = 0;  i < index.Length; i += 2)
            {
                switch (index[i])
                {
                    case 1:
                        cnt1++;
                        val1 = val1 + index[i + 1];
                        break;
                    case 2:
                        cnt2++;
                        val2 = val2 + index[i + 1];
                        break;
                    case 3:
                        cnt3++;
                        val3 = val3 + index[i + 1];
                        break;
                    case 4:
                        cnt4++;
                        val4 = val4 + index[i + 1];
                        break;
                    case 5:
                        cnt5++;
                        val5 = val5 + index[i + 1];
                        break;
                    case 6:
                        cnt6++;
                        val6 = val6 + index[i + 1];
                        break;
                    case 7:
                        cnt7++;
                        val7 = val7 + index[i + 1];
                        break;
                    case 8:
                        cnt8++;
                        val8 = val8 + index[i + 1];
                        break;
                    case 9:
                        cnt9++;
                        val9 = val9 + index[i + 1];
                        break;
                    default:
                        break;
                }
            }
            int total = cnt1 + cnt2 + cnt3 + cnt4 + cnt5 + cnt6 + cnt7 + cnt8 + cnt9;
            decimal avg1 = Convert.ToDecimal(val1) / Convert.ToDecimal(cnt1);
            decimal avg2 = Convert.ToDecimal(val2) / Convert.ToDecimal(cnt2);
            decimal avg3 = Convert.ToDecimal(val3) / Convert.ToDecimal(cnt3);
            decimal avg4 = Convert.ToDecimal(val4) / Convert.ToDecimal(cnt4);
            decimal avg5 = Convert.ToDecimal(val5) / Convert.ToDecimal(cnt5);
            decimal avg6 = Convert.ToDecimal(val6) / Convert.ToDecimal(cnt6);
            decimal avg7 = Convert.ToDecimal(val7) / Convert.ToDecimal(cnt7);
            decimal avg8 = Convert.ToDecimal(val8) / Convert.ToDecimal(cnt8);
            decimal avg9 = Convert.ToDecimal(val9) / Convert.ToDecimal(cnt9);

            Console.WriteLine("{0} pairs of data read.", total);
            Console.WriteLine("The batting average for:");
            Console.WriteLine("   position 1 is {0}", Math.Round(avg1, 4));
            Console.WriteLine("   position 2 is {0}", Math.Round(avg2, 4));
            Console.WriteLine("   position 3 is {0}", Math.Round(avg3, 4));
            Console.WriteLine("   position 4 is {0}", Math.Round(avg4, 4));
            Console.WriteLine("   position 5 is {0}", Math.Round(avg5, 4));
            Console.WriteLine("   position 6 is {0}", Math.Round(avg6, 4));
            Console.WriteLine("   position 7 is {0}", Math.Round(avg7, 4));
            Console.WriteLine("   position 8 is {0}", Math.Round(avg8, 4));
            Console.WriteLine("   position 9 is {0}", Math.Round(avg9, 4));
        }
        catch (System.IO.FileNotFoundException) //file not present
        {
            Console.WriteLine("The file {0} was not found.", doc);
        }
        catch (System.IndexOutOfRangeException)
        {
            Console.WriteLine("Incomplete data pairs. Please re-check your data entries and retry.");
        }
        catch (System.FormatException) //bad data
        {
            Console.WriteLine("Invalid file.");
        }
        catch (System.ArgumentException) //null entry
        {
            Console.WriteLine("Make sure you enter a valid file name.");
        }
        catch (System.Exception exc) //any other exceptions
        {
            Console.WriteLine(exc.Message);
        }
    }
  }
}

I know parts of it are a bit clunky, but as long as it works, I can learn more about condensing the information as I attend more classes. 我知道其中的部分内容有些笨拙,但只要能奏效,我就可以在参加更多课程的同时学习更多有关浓缩信息的信息。 Thank you both for your assistance. 谢谢你们的帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM