二維陣列練習

CSF践行發表於2024-08-25
            //建立一個控制檯應用程式,使用二維陣列儲存火車票資訊,輸入車次和姓名後,模擬預訂火車票功能,程式碼如下:
            string train = "", destination = "", StartTime = "";//宣告3個字串: 車次,車次資訊, 出發時間;
            string[] 標題 = { "車次", "出發站-到達站", "出發時間", "到達時間", "歷時" };//宣告標題;
            //定義二維陣列, 儲存車次資訊;
            string[,] tableValue = {{ "T40","長春-北京","00:12","\t12:20","\t12:08"},
                                    {"T298","長春-北京","00:06","\t10:50","\t10:44" },
                                    {"Z158","長春-北京","12:48","\t21:06","\t08:18" },
                                    {"K1084","長春-北京","12:39","\t02:16","\t13:37" }};
            //遍歷一維陣列, 用來輸出標題:
            for (int i = 0; i < 標題.Length; i++)
            {
                Console.Write(標題[i] + "\t");
            }
            //輸入車次資訊:
            string messages = "";//用來儲存獲取來的車次資訊;
            Console.WriteLine();//換行

            for (int i = 0; i < tableValue.GetLength(0); i++)
            {
                for (int j = 0; j < tableValue.GetLength(1); j++)
                {
                    Console.Write(tableValue[i, j] + "\t");
                }
                train = tableValue[i, 0];
                destination = tableValue[i, 1];
                StartTime =tableValue[i, 2];
                messages += train + "列車"+" "+ destination +" "+ StartTime+" " + "" + ",";
                Console.WriteLine();
            }
            Console.WriteLine("請輸入乘坐車次:");
            string ticket = Console.ReadLine();
            string[] message = messages.Split(',');
            for (int i = 0; i < message.Length-1; i++)//message長度比tableValue的1維長度多1;
            {
                //if (message[i].Contains(ticket))//判斷是否有輸入的車次;
                if (tableValue[i,0]==ticket)//判斷是否有輸入的車次;
                {
                    Console.WriteLine("請輸入您的姓名:");
                    string name = Console.ReadLine();
                    Console.WriteLine(name+"您好,您購買的"+ message[i]+";");

                }
            }
            Console.ReadLine();

相關文章