·二维数组实现出售火车票
按座位购票,若该座位有票则购买成功,否则提示座位已售出。
需求1:先打印一次座位表,每次购买成功或失败都打印座位。
需求2:能正确买票。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace tickets
{
class Program
{
static void Main(string[] args)
{
int[,] tickets = new int[5, 6];
for (int i = 0; i < tickets.GetLength(0); i++)
{
for (int j = 0; j < tickets.GetLength(1); j++)
{
tickets[i, j] = 1;
}
}
while (true)
{
PrintTickets(tickets);
Console.WriteLine("请输入要购买的座位号");
BuyTicket(tickets);
}
}
static void PrintTickets(int[,] tickets)
{
Console.Write(" ");
for (int x = 0; x < tickets.GetLength(1); x++)
{
Console.Write("{0} ", x);
}
Console.WriteLine();
for (int x = 0; x < tickets.GetLength(0); x++)
{
Console.Write(" {0} ", x);
for (int y = 0; y < tickets.GetLength(1); y++)
{
if (tickets[x, y] == 0)
{
Console.Write(" ", x, y);
Console.BackgroundColor = ConsoleColor.DarkRed;
Console.Write(" ", x, y);
Console.BackgroundColor = ConsoleColor.Black;
Console.Write(" ", x, y);
}
else
{
Console.Write(" ", x, y);
Console.BackgroundColor = ConsoleColor.Green;
Console.Write(" ", x, y);
Console.BackgroundColor = ConsoleColor.Black;
Console.Write(" ", x, y);
}
}
Console.BackgroundColor = ConsoleColor.Black;
Console.WriteLine();
Console.WriteLine();
}
}
static int[] InputRowCol()
{
string input = Console.ReadLine();
string[] ss = input.Split(' ', ',', ';');
//Guard Clause 保护性从句
if (ss.Length != 2)
{
return null;
}
int[] ret = new int[2];
if (!int.TryParse(ss[0], out ret[0]))
{
return null;
}
if (!int.TryParse(ss[1], out ret[1]))
{
return null;
}
return ret;
}
static void BuyTicket(int[,] seats)
{
//int row = int.Parse(Console.ReadLine());
//int col = int.Parse(Console.ReadLine());
int[] input = InputRowCol();
if (input == null)
{
Console.WriteLine("输入错误,请重新输入");
return;
}
int row = input[0];
int col = input[1];
if (row < 0 || row >= seats.GetLength(0)
|| col < 0 || col >= seats.GetLength(1))
{
Console.WriteLine("座位不存在,请重新输入");
return;
}
if (seats[row, col] == 0)
{
Console.WriteLine("座位已售出,购买失败");
}
else
{
seats[row, col] = 0;
Console.WriteLine("购买成功");
}
}
}
}
运行效果:
·保护性从句Guard Clause
在InputRowCol函数中用了多个if return应对不同错误状况下的输入,遇到不符合要求的输入时快速跳出,起到保护后面代码的作用。