C#:使用字符串数组列表检查用户输入

时间:2018-10-20 06:58:07

标签: c# arrays string arraylist user-input

基本信息

  • 编程语言:C#(C Sharp)

  • 程序类型:控制台.Net Core 2.0应用程序

  • IDE :Visual Studios社区2017 v15.8.7

程序信息

程序名称:日历计数器

我的程序基础:用户键入一个月,并告诉他们该月有多少天。用户可以自由键入月份名称/身份的任何已知组合(例如3月,3月,3月,3月,3月,3月,03或3)。

我的程序执行:该程序要求用户输入一个月的时间,然后键入。然后,该程序会检查用户在名为String数组的MonthDatabase()方法中键入的内容。如果匹配,它将显示他们键入的月份以及有多少天。

问题信息

程序问题:我的主要问题是找到一种方法来检查用户输入的字符串数组中的内容。我尝试过开关和其他if语句,但是大多数都会给我一个错误(我不会发布所有这些内容)。我还使用字典和列表进行了尝试。每个产生了自己的错误。因此,我回到使用字符串数组的方法,经过多次搜索,然后尝试了各种行不通的方法。我什至试图用谷歌搜索我想要完成的事情(例如用字符串数组检查用户输入)无济于事。目前,我得到的错误是:

  

委托给实例方法不能有空的'this'。

现在是C#(和一般编程)的新手,我只能假设它要我指定要检查的字符串数组以使其与用户输入匹配。我尝试过类似的事情:

Console.Write("Enter a month?: ");
string userMonth = (Console.ReadLine());

if (userMonth == mData(1, 1)) //Compare user input to MonthDataBase
        {
            Console.WriteLine("You typed a word found in the datatbase.");
        }
        else
        {
            Console.WriteLine("You didn't type a word in the datatbase.");
        }

AND

Console.Write("Enter a month?: ");
string userMonth = (Console.ReadLine());

if (userMonth == mData[1, 1]) //Compare user input to MonthDataBase
        {
            Console.WriteLine("You typed a word found in the datatbase.");
        }
        else
        {
            Console.WriteLine("You didn't type a word in the datatbase.");
        }

认为它会查看该位置的字符串并将其匹配,但是显然,我对此假设是错误的。我什至试图通过Google来查看是否有一种方法可以简单地将用户键入的内容与整个字符串数组进行匹配,但是什么也没找到。

我花了一个星期的时间试图弄清这一点,并决定来这里看看是否有人可以向我指出正确的方向。我喜欢学习它的想法,因此,如果可能的话,没有直接答案,例如“这样做”,它将起作用。也许是一个示例(不同,但与我要尝试的操作接近)或“阅读本文档”,它应该会对您有所帮助。

代码

using System;
using System.Collections.Generic;
using System.Linq;

namespace Calendar_Counter
{
    class Program
    {
    public static string mData { get; private set; } //Use mData in any method.

    static void Main(string[] args)
        {
            Header(); //Call Header Method & display
            Menu(); //Call Menu Method & display
            CCDatatbase(); //Call Calendar Counter Database Method, execute & display.

            //Console.WriteLine("Hello World!");
            ExitProgram(); //Call exit program, execute & display
        }
        static void Header()
        {
            Console.Clear(); //Clear console buffer & console window of display information
            Console.Write("--------------------\n| Calendar Counter |\n--------------------\n"); //Display Header text
        }
        static void Menu()
        {
            //ADD menu options once basic program is working!!
            Console.WriteLine(); //Space
            Console.Write("MENU: //ADD menu options once basic program is working!!");
            Console.WriteLine("\n"); //Double Space
        }
        static void CCDatatbase()
        {

            Console.Write("Enter a month?: ");
            string userMonth = (Console.ReadLine());

            if (userMonth.Any(mData.Contains)) //Compare user input to MonthDataBase
            {
                Console.WriteLine("You typed a word found in the datatbase.");
            }
            else
            {
                Console.WriteLine("You didn't type a word in the datatbase.");
            }
        }
        public static string[,] MonthDataBase() //Month Database
        {
            //Check user input with Array List.
            string[,] mData = new string[12, 8]
            {
                { "January", "january", "Jan", "jan", "Jan.", "jan.", "1", "01" }, //If user types 1-8 display corisponding message in CCDatatbase()
                { "January", "january", "Feb", "feb", "Feb.", "feb.", "2", "02" },
                { "March", "march", "Mar", "mar", "Mar.", "mar.", "3", "03" },
                { "April", "april", "Apr", "apr", "Apr.", "apr.", "4", "04" },
                { "May", "may", "May", "may", "May", "may", "5", "05" },
                { "June", "june", "Jun", "jun", "Jun.", "jun.", "6", "06" },
                { "July", "july", "Jul", "jul", "Jul.", "jul.", "7", "07" },
                { "August", "august", "Aug", "aug", "Aug.", "aug.", "8", "08" },
                { "September", "september", "Sep", "sep", "Sep.", "sep.", "9", "09" },
                { "October", "october", "Oct", "oct", "Oct.", "oct.", "10", "10" },
                { "November", "november", "Nov", "nov", "Nov.", "nov.", "11", "11" },
                { "December", "december", "Dec", "dec", "Dec.", "dec.", "12", "12" }
            };

            return mData;
        }
        static void ExitProgram()
        {
            //REPLACE later with an actual exit option in menu!!
            Console.Write("EXIT: //REPLACE later with an actual exit option in menu!!\n\n");
            //Prevent Debugging test from closing.
            Console.Write("Press any key to Exit...");
            Console.ReadLine();
        }
    }
}

2 个答案:

答案 0 :(得分:1)

如果您无意将其设为二维数组,那么我建议您创建一个类。从长远来看,一个类将简化许多事情,而不是在这种情况下依赖于二维数组。

这是我解决问题的方法。

  1. 我创建了一个名为Month的类(可以根据需要更改名称)。

  2. “ Month”类具有一个List属性MonthNames,如下所示,

      public class Month {
      public List<string> MonthNames { get; set; }
    
      public Month()
      {
          MonthNames = new List<string>();
      } }
    
  3. 在GetMonths()方法中按以下方式创建“月”类型的对象。 (在这种情况下,您可以放弃MonthDataBase()方法。)

          private static List<Month> GetMonths()
          {
              var months = new List<Month>();
              var month = new Month();
              month.MonthNames.Add("January");
              month.MonthNames.Add("january");
              month.MonthNames.Add("Jan");
              month.MonthNames.Add("01");
              months.Add(month);
    
              month = new Month();
              month.MonthNames.Add("Feburary");
              month.MonthNames.Add("feburary");
              month.MonthNames.Add("Feb");
              month.MonthNames.Add("02");
              months.Add(month);
              // Similary add all other to the list.
    
              return months;
          }
    
  4. 这是其余的代码(您可以在程序中的任意位置添加以下代码)

              Console.Write("Enter a month?: ");
              var userMonth = (Console.ReadLine());
              var months = GetMonths();
    
              var result = months.Where(x => x.MonthNames.Any(y => y.Equals(userMonth))).ToList();
    

注意:-我已返回为ToList(),但是在您的情况下,您可以返回为FirstOrDefault()。 因此,现在您有了一个“月”对象,并且可以根据数据打印“否”。几天或做其他事情取决于您。

希望您很清楚。尝试一下,让我们知道是否有任何错误或疑问。

答案 1 :(得分:0)

  1. 尝试将MonthDataBase方法的返回类型更改为List<List<string>>

  2. 尝试将mData公共属性的签名更改为public static List<List<string>> mData { get; private set; }

  3. 使用mData之类的CCDatatbase方法填充属性mData = MonthDataBase();上方

  4. 然后检查输入的字符串是否出现在mData中。

所以最终您的程序将成为

class Program
{
    public static List<List<string>> mData { get; private set; } //Use mData in any method.

    static void Main(string[] args)
    {
        Header();       // Call Header Method & display
        Menu();         // Call Menu Method & display
        CCDatabase();   // Call Calendar Counter Database Method, execute & display.

        //Console.WriteLine("Hello World!");
        ExitProgram(); //Call exit program, execute & display
    }

    static void Header()
    {
        Console.Clear(); //Clear console buffer & console window of display information
        Console.Write("--------------------\n| Calendar Counter |\n--------------------\n"); //Display Header text
    }

    static void Menu()
    {
        //ADD menu options once basic program is working!!
        Console.WriteLine(); //Space
        Console.Write("MENU: //ADD menu options once basic program is working!!");
        Console.WriteLine("\n"); //Double Space
    }

    static void CCDatabase()
    {
        mData = MonthDataBase();
        Console.Write("Enter a month?: ");
        string userMonth = (Console.ReadLine());

        if (mData.Any(x => x.Contains(userMonth))) //Compare user input to MonthDataBase
        {
            var month = mData.Where(x => x.Contains(userMonth)).Select(x => new { Days = x[0], Name = x[1] }).FirstOrDefault();
            Console.WriteLine($"{month.Name} has {month.Days} days in it.");
            Console.WriteLine();
        }
        else
        {
            Console.WriteLine("You didn't type a word in the database.");
            Console.WriteLine();
        }
    }

    public static List<List<string>> MonthDataBase() //Month Database
    {
        var mData = new List<List<string>>  {
      new List<string>  { "31", "January", "january", "Jan", "jan", "Jan.", "jan.", "1", "01" }, //If user types 1-8 display corresponding message in CCDatatbase()
      new List<string>  { "28/29", "February", "february", "Feb", "feb", "Feb.", "feb.", "2", "02" },
      new List<string>  { "31", "March", "march", "Mar", "mar", "Mar.", "mar.", "3", "03" },
      new List<string>  { "30", "April", "april", "Apr", "apr", "Apr.", "apr.", "4", "04" },
      new List<string>  { "31", "May", "may", "May", "may", "May", "may", "5", "05" },
      new List<string>  { "30", "June", "june", "Jun", "jun", "Jun.", "jun.", "6", "06" },
      new List<string>  { "31", "July", "july", "Jul", "jul", "Jul.", "jul.", "7", "07" },
      new List<string>  { "31", "August", "august", "Aug", "aug", "Aug.", "aug.", "8", "08" },
      new List<string>  { "30", "September", "september", "Sep", "sep", "Sep.", "sep.", "9", "09" },
      new List<string>  { "31", "October", "october", "Oct", "oct", "Oct.", "oct.", "10", "10" },
      new List<string>  { "30", "November", "november", "Nov", "nov", "Nov.", "nov.", "11", "11" },
      new List<string>  { "31", "December", "december", "Dec", "dec", "Dec.", "dec.", "12", "12" }
    };

        return mData;
    }

    static void ExitProgram()
    {
        //REPLACE later with an actual exit option in menu!!
        Console.Write("EXIT: //REPLACE later with an actual exit option in menu!!\n\n");
        //Prevent Debugging test from closing.
        Console.Write("Press any key to Exit...");
        Console.ReadLine();
    }
}

输入:七月

输出:

enter image description here

输入: 04

输出:

enter image description here

输入: abcd

输出:

enter image description here