首页 > 解决方案 > 无法获得价值

问题描述

首先,这是我的第一个问题,很抱歉没有遵循指导方针,我的错,下次会做得更好。

简而言之,我在一个 CSV 文件中绘制了乐透值,我可以读取这些值并将它们放入一个数组中。一旦进入数组,我必须对每一行(球)应用一些统计公式,所以我基本上创建另一个数组来保存这些值。但似乎我没有宣布它足够高。

到目前为止,我收到了一些评论,但并没有真正困扰我。它与如何使“tirages”全球化有关,以便我可以在整个代码中访问其内容?

如果你查看代码,大约第 40 行你会看到这个......

int derniertirageacompter = tirages.Count;
Console.WriteLine($"dernier tirage: {derniertirageacompter}")

...返回0。但我在“Load_649_CSV”中的其他地方引用了tirages,它工作正常。我尝试了视觉工作室提出的解决方案,但没有奏效,所以我在这里。

我相信问题在于“tirages”以及它是如何/在哪里宣布的,但我不知道。显然,我不是程序员!20 年前我在 Excel VBA 中编写了一个程序,我正在尝试用 c# 重写它。我将不得不使用大量的数组来重新创建我使用的存储公式和数据的电子表格。这就是我试图在全球范围内访问 tirages 的原因。

...

//Main Program
//
namespace Lotto_649
{
    class Program
    {
        //public static object Frequence { get; private set; }

        static void Main(string[] args)
        {
            int Nb_Boule;//49 for 649 and 50 for Lotto_MAX
            
            MenuPrincipale();//display the main menu

            //load the draw based on the choice
            int Menu_Lotto_Choice = Convert.ToInt16(Console.ReadLine());
            switch (Menu_Lotto_Choice)//faire une selection
            {
                case 1:
                    Console.WriteLine("Loading 649");
                    Load_649_CSV();//call method for loading the 649 drwas
                    Nb_Boule = 49;
                    break;
                case 2:
                    Console.WriteLine("To Do Lotto MAX");
                    //Load_Lotto_max();//call method for the lotto max draw 
                    Nb_Boule = 50;
                    break;
                default:
                    Console.WriteLine("Error - Break");//any other keys
                    break;
            }//end switch

            //this is where I have I think an issue!
            var tirages = new List<Tirage>();

            int derniertirageacompter = tirages.Count;
            Console.WriteLine($"dernier tirage: {derniertirageacompter}");
        }

        //---------------------------Declaring the method used in the main program

        //Load the 649 draw in the array. 
        public static void Load_649_CSV()
        {
            //read the content of the CSV file as plain text
            //read all the lines and put it directly into an array
            //Date,Boule 1,Boule 2,Boule 3,Boule 4,Boule 5,Boule 6,Complementaire,Valeur,Even - Odd,Buckets

            string[] csvAllTirage649 = System.IO.File.ReadAllLines(@"C:\Users\repos\CSV-Reader-with-lotto\Tirage649.csv");
            int Num_of_Draw_to_Check;//variable that determine how many draw to check
               
            //**Declaring the array tirages**
            //How to declare the array so its available globally? is this the way to do it?
             var tirages = new List<Tirage>();

            Console.WriteLine($"There are {csvAllTirage649.Length} in the file.");
            Console.WriteLine($"How many resutls to load?");
            string v = Console.ReadLine();
            //**add error catcher

            Num_of_Draw_to_Check = Convert.ToInt16(v);

            for (int i = 1; i < Num_of_Draw_to_Check; i++)//start with 1 since 0 content the header
            {
                Tirage draw = new Tirage(csvAllTirage649[i]);//creat the array drawy abd laod the results into it.
                tirages.Add(draw);
            }
            Console.WriteLine($"The {Num_of_Draw_to_Check} sesutls are loaded");
        }// End Load_649_CSV
       
        //----------------------Print to screen the menu---------------------------------
        private static void MenuPrincipale()
        {
            //menu principale
            Console.WriteLine($"-------------------------------");
            Console.WriteLine($"Beginning of the program");
            Console.WriteLine($"Select the lotto type");
            Console.WriteLine($"1 - 649");
            Console.WriteLine($"2 - Lotto Max");
            Console.WriteLine($"-------------------------------");
            //end menuprincipale
        }
    }
}

...

这是我的课...

namespace Lotto_649
{
    //on defini la classe tirage qui est utiliser pour lire le fichier CSV
    public class Tirage
    {
        public DateTime t_Date;
        public int B1, B2, B3, B4, B5, B6, Comp, Somme_Tir_wo_Compl, Pair;
        //should I use and array to store the boule value?
        //public int[] Boules = new int[6];
        public string Montant, Even_Odd, Bucket;

        public Tirage(string rowTirage649)
        {
            // Date,Boule 1,Boule 2,Boule 3,Boule 4,Boule 5,Boule 6,Complementaire,Valeur,Even - Odd,Buckets
            
            string[] data = rowTirage649.Split(',');
            //parse data into properties
            //convert from a string to a date
            this.t_Date = Convert.ToDateTime(data[0]);
            //convert from a string to int
            this.B1 = Convert.ToInt16(data[1]);
            this.B2 = Convert.ToInt16(data[2]);
            this.B3 = Convert.ToInt16(data[3]);
            this.B4 = Convert.ToInt16(data[4]);
            this.B5 = Convert.ToInt16(data[5]);
            this.B6 = Convert.ToInt16(data[6]);
            this.Comp = Convert.ToInt16(data[7]);
            this.Montant = data[8];
            this.Even_Odd = data[9];
            this.Bucket = data[10];

            this.Somme_Tir_wo_Compl = B1 + B2 + B3 + B4 + B5 + B6;

            //init Pair, then count the nombre de boule pair.
            Pair = 0;
            {
                if (B1 % 2 == 0)
                    Pair++;
                if (B2 % 2 == 0)
                    Pair++;
                if (B3 % 2 == 0)
                    Pair++;
                if (B4 % 2 == 0)
                    Pair++;
                if (B5 % 2 == 0)
                    Pair++;
                if (B6 % 2 == 0)
                    Pair++;
            }

        }

        public override string ToString()
        {
            string str = $"{t_Date} {B1} {B2} {B3} {B4} {B5} {B6} {Comp} {Montant} {Even_Odd} {Pair}:";
            return str;
        }
    }
}

...

标签: c#classmethods

解决方案


下面的代码是您的代码,经过一些修改。我在代码中添加了一些注释。根据您的要求/目标,可能需要对以下代码进行进一步修改。

由于它主要是您的代码,因此似乎不需要提供很多解释。

资源

创建一个名为“Tirage”的类。

Tirage.cs

namespace Lotto_649
{
    //on defini la classe tirage qui est utiliser pour lire le fichier CSV
    public class Tirage
    {
        public DateTime t_Date { get; set; } = DateTime.MinValue;
        public int B1 { get; set; } = 0;
        public int B2 { get; set; } = 0;
        public int B3 { get; set; } = 0;
        public int B4 { get; set; } = 0;
        public int B5 { get; set; } = 0;
        public int B6 { get; set; } = 0;
        public int Comp { get; set; } = 0;
        public int Somme_Tir_wo_Compl { get; set; } = 0;
        public int Pair { get; set; } = 0;
        public string Montant { get; set; } = string.Empty;
        public string Even_Odd { get; set; } = string.Empty;
        public string Bucket { get; set; } = string.Empty;

        public Tirage(DateTime t_Date, int b1, int b2, int b3, int b4, int b5, int b6, int comp, string montant, string even_odd, string bucket)
        {
            // Date,Boule 1,Boule 2,Boule 3,Boule 4,Boule 5,Boule 6,Complementaire,Valeur,Even - Odd,Buckets

            this.t_Date = t_Date;

            this.B1 = b1;
            this.B2 = b2;
            this.B3 = b3;
            this.B4 = b4;
            this.B5 = b5;
            this.B6 = b6;
            this.Comp = comp;
            this.Montant = montant;
            this.Even_Odd = even_odd;
            this.Bucket = bucket;

            this.Somme_Tir_wo_Compl = B1 + B2 + B3 + B4 + B5 + B6;

            // count the nombre de boule pair.

            if (B1 % 2 == 0)
                Pair++;
            if (B2 % 2 == 0)
                Pair++;
            if (B3 % 2 == 0)
                Pair++;
            if (B4 % 2 == 0)
                Pair++;
            if (B5 % 2 == 0)
                Pair++;
            if (B6 % 2 == 0)
                Pair++;

        }

        public override string ToString()
        {
            string str = $"{t_Date.ToString("yyyy-MM-dd")} {B1} {B2} {B3} {B4} {B5} {B6} {Comp} {Montant} {Even_Odd} {Pair}";
            return str;
        }
    }
}

您会在下面的代码中注意到以下内容:

do
{
    ...

} while (true);

这是一个无限循环。break用于在满足所需条件后退出循环。

对于“Program.cs”中的代码,下面我将展示两个不同的选项。实现相同结果是两种不同的解决方案。

选项 1,将使用允许多个方法访问变量包含的数据的类变量。

选项 1 -(概述):

在下面的示例中,请注意MenuPrincipale返回类型为void. 由于s_MenuLottoChoice, 是一个类变量,它可以被类中的任何方法访问。

class Program
{
    private static int s_MenuLottoChoice = 0;

    static void Main(string[] args)
    {
                    ...

        MenuPrincipale();

                    ...

        switch (s_MenuLottoChoice)
        {
                    ...
        }

                    ...
    }

    private static void MenuPrincipale()
    {
                    ...

        Console.WriteLine($"-------------------------------");
        Console.WriteLine($"Select the lotto type");
        Console.WriteLine($"1 - 649");
        Console.WriteLine($"2 - Lotto Max");
        Console.WriteLine($"Q - Quit Program");
        Console.WriteLine($"-------------------------------");
        Console.Write($"Enter selection: ");

        string userSelection = Console.ReadLine().Trim();

        //try to convert to int
        bool parseSucceeded = Int32.TryParse(userSelection, out s_MenuLottoChoice);

                    ...
    }
}

选项 1 - Program.cs(完整代码)

namespace Lotto_649
{
    class Program
    {
        private static string s_csvFilename = @"C:\Users\repos\CSV-Reader-with-lotto\Tirage649.csv";
        private static List<Tirage> s_tirages = new List<Tirage>();
        private static int s_MenuLottoChoice = 0;

        static void Main(string[] args)
        {

            int nbBoule = 0;//49 for 649 and 50 for Lotto_MAX

            //load the draw based on the choice
            MenuPrincipale();

            switch (s_MenuLottoChoice)//faire une selection
            {
                case 1:
                    Console.WriteLine("Loading 649");
                    Load649Csv();//call method for loading the 649 drwas
                    nbBoule = 49;
                    break;
                case 2:
                    Console.WriteLine("To Do Lotto MAX");
                    //LoadLottoMax();//call method for the lotto max draw 
                    nbBoule = 50;
                    break;
                default:
                    Console.WriteLine("Error - Break");//any other keys
                    break;
            }//end switch

            //int dernierTirageACompter = s_tirages.Count;
            //Console.WriteLine($"dernier tirage: {dernierTirageACompter}");
            Console.WriteLine($"dernier tirage: {s_tirages.Count}");


            DisplayData(); //display data

        }

        //---------------------------Declaring the method used in the main program

        //Display data
        public static void DisplayData()
        {
            //output results
            if (s_tirages != null)
            {
                foreach (Tirage t in s_tirages)
                {
                    Console.WriteLine(t.ToString());
                }
            }
            else
            {
                Console.WriteLine($"Error: s_tirages is null");
            }
        }

        //Load the 649 draw in the array. 
        public static void Load649Csv()
        {
            //check if filename exists
            if (!System.IO.File.Exists(s_csvFilename))
            {
                Console.WriteLine($"Error: File doesn't exist: '{s_csvFilename}'");
                return;
            }

            //read the content of the CSV file as plain text
            //read all the lines and put it directly into an array
            //Date,Boule 1,Boule 2,Boule 3,Boule 4,Boule 5,Boule 6,Complementaire,Valeur,Even - Odd,Buckets

            string[] csvAllTirage649 = System.IO.File.ReadAllLines(s_csvFilename);

            int numDrawToCheck = 0;//how many draws to check


            //since 1st line is header, need to subtract 1 
            Console.WriteLine($"There are {csvAllTirage649.Length - 1} entries in the file.");

            //prompt user for selection
            //if an invalid entry was made, re-prompt
            do
            {
                Console.Write($"How many results to load? ");

                //get user selection
                //remove any leading/trailing spaces and newline
                string userSelection = Console.ReadLine().Trim();

                //convert to int
                Int32.TryParse(userSelection, out numDrawToCheck);

                if (numDrawToCheck < 1 || numDrawToCheck > csvAllTirage649.Length - 1)
                {
                    //inform user of invalid selection
                    Console.WriteLine($"\nError: Invalid selection '{userSelection}'. Please try again.\n");
                }
                else
                {
                    //user selection is valid. exit loop
                    break;
                }
            } while (true);
           
            if (csvAllTirage649 != null && csvAllTirage649.Length > 1)
            {
                for (int i = 1; i <= numDrawToCheck; i++)//start with 1 since the first line is the content header
                {
                    string[] data = csvAllTirage649[i].Split(',');

                    //ToDo: ensure date format is correct
                    DateTime t_Date = DateTime.ParseExact(data[0].Trim(), "yyyy-MM-dd", System.Globalization.CultureInfo.InvariantCulture);

                    int b1 = 0;
                    int b2 = 0;
                    int b3 = 0;
                    int b4 = 0;
                    int b5 = 0;
                    int b6 = 0;
                    int comp = 0;
                    string montant = string.Empty;
                    string even_odd = string.Empty;
                    string bucket = string.Empty;

                    Int32.TryParse(data[1], out b1); //try to convert to int
                    Int32.TryParse(data[2], out b2); //try to convert to int
                    Int32.TryParse(data[3], out b3); //try to convert to int
                    Int32.TryParse(data[4], out b4); //try to convert to int
                    Int32.TryParse(data[5], out b5); //try to convert to int
                    Int32.TryParse(data[6], out b6); //try to convert to int
                    Int32.TryParse(data[7], out comp); //try to convert to int

                    montant = data[8].Trim();
                    even_odd = data[9].Trim();
                    bucket = data[10].Trim();

                    //add to list
                    s_tirages.Add(new Tirage(t_Date, b1, b2, b3, b4, b5, b6, comp, montant, even_odd, bucket));
                }
            }
            
            Console.WriteLine($"{s_tirages.Count} results are loaded");
   
        }// End Load649Csv

        //----------------------Print to screen the menu---------------------------------
        private static void MenuPrincipale()
        {
            //prompt user for selection
            //if an invalid entry was made, re-prompt
            //allow the user to exit the program if desired
            do
            {
                Console.WriteLine($"-------------------------------");
                Console.WriteLine($"Select the lotto type");
                Console.WriteLine($"1 - 649");
                Console.WriteLine($"2 - Lotto Max");
                Console.WriteLine($"Q - Quit Program");
                Console.WriteLine($"-------------------------------");
                Console.Write($"Enter selection: ");

                //get user selection
                //remove any leading/trailing spaces and newline
                string userSelection = Console.ReadLine().Trim();

                //try to convert to int
                bool parseSucceeded = Int32.TryParse(userSelection, out s_MenuLottoChoice);

                if (userSelection == "Q" || userSelection == "q")
                {
                    //exit the program
                    Environment.Exit(0);
                }
                else if (s_MenuLottoChoice < 1 || s_MenuLottoChoice > 2)
                {
                    //inform user of invalid selection
                    Console.WriteLine($"\nError: Invalid selection {userSelection}. Please try again.\n");
                }
                else
                {
                    break; //exit loop
                }

            } while (true);
            //menu principale

            //end menuprincipale
        }
    }
}

选项 2,将通过从被调用的方法返回数据将数据传递回调用方法。

选项 2 -(概述):

在下面的示例中,请注意MenuPrincipale返回类型为int. 该方法必须返回一个int值。的值result是通过从方法中返回来提供的。

class Program
{
    static void Main(string[] args)
    {
                    ...

        int menuLottoChoice = MenuPrincipale();

                    ...

        switch (menuLottoChoice)
        {
                    ...
        }

                    ...
    }

    private static int MenuPrincipale()
    {
        int result = 0;

                    ...

        Console.WriteLine($"-------------------------------");
        Console.WriteLine($"Select the lotto type");
        Console.WriteLine($"1 - 649");
        Console.WriteLine($"2 - Lotto Max");
        Console.WriteLine($"Q - Quit Program");
        Console.WriteLine($"-------------------------------");
        Console.Write($"Enter selection: ");

        string userSelection = Console.ReadLine().Trim();

        //try convert to int
        bool parseSucceeded = Int32.TryParse(userSelection, out result);

                    ...

        return result;   
    }
}

选项 2 - Program.cs(完整代码)

namespace Lotto_649
{
    class Program
    {
        private static string s_csvFilename = @"C:\Users\repos\CSV-Reader-with-lotto\Tirage649.csv";

        static void Main(string[] args)
        {
            List<Tirage> tirages = new List<Tirage>();

            int nbBoule;//49 for 649 and 50 for Lotto_MAX

            //load the draw based on the choice
            int menuLottoChoice = MenuPrincipale();

            switch (menuLottoChoice)//faire une selection
            {
                case 1:
                    Console.WriteLine("Loading 649");
                    tirages = Load649Csv();//call method for loading the 649 drwas
                    nbBoule = 49;
                    break;
                case 2:
                    Console.WriteLine("To Do Lotto MAX");
                    //LoadLottoMax();//call method for the lotto max draw 
                    nbBoule = 50;
                    break;
                default:
                    Console.WriteLine("Error - Break");//any other keys
                    break;
            }//end switch

            //int dernierTirageACompter = tirages.Count;
            //Console.WriteLine($"dernier tirage: {dernierTirageACompter}");
            Console.WriteLine($"dernier tirage: {tirages.Count}");

            DisplayData(tirages); //display data

        }

        //---------------------------Declaring the method used in the main program

        //Display Dat
        public static void DisplayData(List<Tirage> tirages)
        {
            //output results
            if (tirages != null)
            {
                foreach (Tirage t in tirages)
                {
                    Console.WriteLine(t.ToString());
                }
            }
            else
            {
                Console.WriteLine($"Error: s_tirages is null");
            }
        }

        //Load the 649 draw in the array. 
        public static List<Tirage> Load649Csv()
        {
            var tirages = new List<Tirage>();

            //check if filename exists
            if (!System.IO.File.Exists(s_csvFilename))
            {
                Console.WriteLine($"Error: File doesn't exist: '{s_csvFilename}'");
                return null;
            }

            //read the content of the CSV file as plain text
            //read all the lines and put it directly into an array
            //Date,Boule 1,Boule 2,Boule 3,Boule 4,Boule 5,Boule 6,Complementaire,Valeur,Even - Odd,Buckets
            string[] csvAllTirage649 = System.IO.File.ReadAllLines(s_csvFilename);

            int numDrawToCheck = 0;//how many draws to check


            //since 1st line is header, need to subtract 1 
            Console.WriteLine($"There are {csvAllTirage649.Length - 1} entries in the file.");

            //prompt user for selection
            //if an invalid entry was made, re-prompt
            do
            {
                Console.Write($"How many results to load? ");

                //get user selection
                //remove any leading/trailing spaces and newline
                string userSelection = Console.ReadLine().Trim();

                //try to convert to int
                bool parseSucceeded = Int32.TryParse(userSelection, out numDrawToCheck);

                if (numDrawToCheck < 1 || numDrawToCheck > csvAllTirage649.Length - 1)
                {
                    //inform user of invalid selection
                    Console.WriteLine($"\nError: Invalid selection '{userSelection}'. Please try again.\n");
                }
                else
                {
                    //user selection is valid. exit loop
                    break;
                }
            } while (true);
           
            if (csvAllTirage649 != null && csvAllTirage649.Length > 1)
            {
                for (int i = 1; i <= numDrawToCheck; i++)//start with 1 since 0 content the header
                {
                    string[] data = csvAllTirage649[i].Split(',');

                    //ToDo: ensure date format is correct
                    DateTime t_Date = DateTime.ParseExact(data[0].Trim(), "yyyy-MM-dd", System.Globalization.CultureInfo.InvariantCulture);

                    int b1 = 0;
                    int b2 = 0;
                    int b3 = 0;
                    int b4 = 0;
                    int b5 = 0;
                    int b6 = 0;
                    int comp = 0;
                    string montant = string.Empty;
                    string even_odd = string.Empty;
                    string bucket = string.Empty;

                    Int32.TryParse(data[1], out b1);
                    Int32.TryParse(data[2], out b2);
                    Int32.TryParse(data[3], out b3);
                    Int32.TryParse(data[4], out b4);
                    Int32.TryParse(data[5], out b5);
                    Int32.TryParse(data[6], out b6);
                    Int32.TryParse(data[7], out comp);

                    montant = data[8].Trim();
                    even_odd = data[9].Trim();
                    bucket = data[10].Trim();

                    //add to list
                    tirages.Add(new Tirage(t_Date, b1, b2, b3, b4, b5, b6, comp, montant, even_odd, bucket));
                }
            }
            
            Console.WriteLine($"{tirages.Count} results are loaded");
   
            return tirages;
        }// End Load649Csv

        //----------------------Print to screen the menu---------------------------------
        private static int MenuPrincipale()
        {
           
            int result = 0;

            do
            {
                Console.WriteLine($"-------------------------------");
                Console.WriteLine($"Select the lotto type");
                Console.WriteLine($"1 - 649");
                Console.WriteLine($"2 - Lotto Max");
                Console.WriteLine($"Q - Quit Program");
                Console.WriteLine($"-------------------------------");
                Console.Write($"Enter selection: ");

                string userSelection = Console.ReadLine().Trim();

                //try convert to int
                bool parseSucceeded = Int32.TryParse(userSelection, out result);

                if (userSelection == "Q" || userSelection == "q")
                {
                    //exit the program
                    Environment.Exit(0);
                }
                else if (result < 1 || result > 2)
                {
                    //inform user of invalid selection
                    Console.WriteLine($"\nError: Invalid selection {userSelection}. Please try again.\n");
                }
                else
                {
                    //user selection is valid. exit loop
                    break;
                }

            } while (true);
            //menu principale

            return result;
            
            //end menuprincipale
        }
    }
}

使用了以下测试数据,但由于仅提供了单行测试数据,因此可能无效。做出假设是为了创建额外的测试数据。

Tirage649.csv

Date, Boule 1, Boule 2, Boule 3, Boule 4, Boule 5, Boule 6, Complementaire, Valeur, Even - Odd, Buckets
2021-06-04, 5, 10, 12, 25, 27, 32, 3, 111M, 2O, 32453
2021-06-02, 3, 15, 22, 24, 28, 34, 2, 126M, 5E, 32454
2021-05-30, 1, 11, 20, 23, 26, 30, 5, 111M, 3O, 32455
2021-05-25, 4, 12, 18,1 9, 21, 29, 15, 118M, 6E, 32456
2021-03-21, 3, 5, 12, 23, 35, 49, 23, 45M, 3E, 32452 

推荐阅读