面试题

4、一个文本文件含有如下内容,分别表示姓名和成绩:
张三90
李四96
王五78
赵六82

提供用户一个控制台界面,允许用户输入要查询的姓名,输入姓名并且按回车以
后,打印出此人的成绩,如果不输入姓名直接按回车则显示所有人的姓名以及成
绩。(注意:不能使用数据库)

class Program
    {
        static void Main(string[] args)
        {
            //定义文本文件路径
            string file = "F:/Itcast/Itcast/Itcast/file/1.txt";
            //将文本文件数据读取到内存中
            string content =File.ReadAllText(file,Encoding.Default);
            //对数据进行拆分成数组
            string[] array = content.Split('
');
            //定义字段
            Dictionary<string, string> dict = new Dictionary<string, string>();
            for (int i = 0; i < array.Length; i++)
            {
                //将回车字符替换掉
                string record = array[i].Replace("
", "");
                //获取名字
                string l_name = record.Split(' ')[0];
                //获取分数
                string l_score = record.Split(' ')[1];
                //将数据添加到字典中
                dict.Add(l_name,l_score);
            }
            while (true)
            {
                Console.WriteLine("请输入要查询的姓名:");
                string name = Console.ReadLine().Trim();
                if (string.IsNullOrEmpty(name))
                {
                    foreach (KeyValuePair<string,string> kvp in dict)
                    {
                        Console.WriteLine(kvp.Key+"  "+kvp.Value);
                    }
                }
                else
                {
                    try
                    {
                        Console.WriteLine(dict[name]);
                    }
                    catch(Exception ex)
                    {
                        Console.WriteLine(ex.Message);
                    }
                }
            }
        }
    
}

  

原文地址:https://www.cnblogs.com/mdy41034264/p/3305465.html