具体要求为:
使用一个二维数组记录客车售票系统中的所有座位号,并在每个座位号上都显示有票,然后用户输入一个坐标位置,按Enter键,即可将该座位号显示为已售。
首先我定义的输入格式为:1,2
个人认为主要知识点伪代码如下
1.字符串分割
char[] separator = { ',' };
splitstrings = str.Split(separator);
2.字符串前后去空
str.Trim()
3.转换类型,如果不是int类型则为false,可以处理异常情况。
int columnNum = 0;
bool isColumn = int.TryParse(column, out columnNum);
先创建如下脚本,然后在Main函数中直接调用即可。
1 public class TicketingSystem 2 { 3 int[,] seatCount = new int[9, 4]; 4 5 public void CheckTicketCount() 6 { 7 bool res = true; 8 String[] splitstrings = { "row", "col"}; 9 char[] separator = { ',' }; 10 while (res) 11 { 12 Console.WriteLine("请输入座位号:"); 13 string str = Console.ReadLine(); 14 splitstrings = str.Split(separator); 15 if (str.Trim() == "Quit") 16 { 17 res = false; 18 Console.WriteLine("结束购票"); 19 return; 20 } 21 22 if (splitstrings.Length < 2) 23 { 24 Console.WriteLine("输入的格式不正确"); 25 continue; 26 } 27 string row = splitstrings[0].Trim(); 28 string column = splitstrings[1].Trim(); 29 30 int rowNum = 0; 31 bool isRow = int.TryParse(row, out rowNum); 32 if (!isRow || rowNum >= seatCount.GetLength(0)) 33 { 34 Console.WriteLine("输入的行不正确"); 35 continue; 36 } 37 38 int columnNum = 0; 39 bool isColumn = int.TryParse(column, out columnNum); 40 if (!isColumn || columnNum >= seatCount.GetLength(1)) 41 { 42 Console.WriteLine("输入的列不正确"); 43 continue; 44 } 45 if (seatCount[rowNum, columnNum] == 1) 46 { 47 Console.WriteLine("该座位已经被购买!"); 48 continue; 49 } 50 seatCount[rowNum, columnNum] = 1; 51 Console.WriteLine(rowNum + "行" + columnNum + "列车票售出"); 52 bool isEmptySeat = false; 53 for (int i = 0; i < seatCount.GetLength(0); i++) 54 { 55 for (int j = 0; j < seatCount.GetLength(1); j++) 56 { 57 if (seatCount[i, j] == 0) 58 { 59 isEmptySeat = true; 60 break; 61 } 62 } 63 if (isEmptySeat) 64 { 65 break; 66 } 67 } 68 69 if (!isEmptySeat) 70 { 71 res = false; 72 Console.WriteLine("车票售完!"); 73 return; 74 } 75 Console.WriteLine(); 76 Console.WriteLine(); 77 } 78 } 79 }