【问题标题】:How to prevent FormatException and IndexOutOfRangeException?如何防止 FormatException 和 IndexOutOfRangeException?
【发布时间】:2015-12-22 23:46:59
【问题描述】:

当用户在将字符串转换为 int 时输入错误的输入时,此代码将引发格式异常。当售出 32 张票时,它也没有达到“所有头等舱座位都已预订”的预期输出,它只是抛出了一个 index out of range 异常。对此的任何帮助将不胜感激。谢谢。

class FirstClassCompartment
{ 
    public void FirstClassTickets()
    {
        bool[] seats = new bool[32];
        List<int> seatsBooked = new List<int>();
        int completeBooking = 0;
        bool quit = false;
        string ticketAmount = "";
        int firstClassSeat = 0;
        int convertedTicketAmount;
        {
            Groups firstClass = new Groups();
            Console.Clear();
            Console.WriteLine("\nWelcome to the First Class booking menu");
            Console.WriteLine("");
            Console.WriteLine("Please enter the amount of tickets you would like to book");
            ticketAmount = Console.ReadLine();
            Console.Clear();
            Console.WriteLine("\nFirst Class booking menu");
                    convertedTicketAmount = Convert.ToInt32(ticketAmount);
                    ticketAmount = firstClass.NumberInGroupFirstClassWest;
        }

        do
        {
            Console.Clear();
            Console.WriteLine("\nFirst Class booking menu");
            Console.WriteLine("");
            Console.WriteLine("Please press 1 to complete your first class booking");
            completeBooking = Int32.Parse(Console.ReadLine());

            switch (completeBooking)
            {
                case 1:

                    if (seatsBooked.Count == 0)
                    {
                        firstClassSeat++;
                        seats[firstClassSeat] = true;
                        seatsBooked.Add(firstClassSeat);
                    }
                    else
                    {

                        do
                        {
                            firstClassSeat++;
                            if (!seatsBooked.Contains(firstClassSeat))
                            {
                                seats[firstClassSeat] = true;

                            }
                        }
                        while (seatsBooked.Contains(firstClassSeat) && seatsBooked.Count < 32);
                        if (seatsBooked.Count < 32)
                        {
                            seatsBooked.Add(firstClassSeat);
                        }
                    }
                    if (seatsBooked.Count > 32)
                    {
                        Console.WriteLine("All seats for first class have been booked");
                        Console.WriteLine("Please press enter to continue...");

                    }
                    else
                    {
                        Console.WriteLine("Your seat: {0}", firstClassSeat + 1);
                        Console.WriteLine("Please press enter to continue...");

                    }
                    Console.ReadLine();
                    break;
                default:
                    Console.WriteLine("\nPlease enter a valid input");
                    quit = true;
                    break;
            }
        } while (!quit);
    }
}

【问题讨论】:

  • 您需要使用Int.TryParse(),如果返回false,则向用户显示错误。

标签: c# exception formatexception indexoutofrangeexception


【解决方案1】:

您需要使用Int32.TryParse并检查返回的bool

看看你 switch 语句中的逻辑,你只处理 1 的预订。如果用户预订 2 个座位怎么办?
编辑:抱歉,刚刚意识到 switch 语句是处理菜单,而不是预订数量

您是否需要ints 的列表以及bools 的数组来跟踪已预订的座位数?你不能只使用一个普通的旧int,例如numberOfSeatsBooked?那你就可以numberOfSeatsBooked += convertedTicketAmount;

【讨论】:

  • 我还没有走到那一步,我只是想先摆脱这些异常。此外,列表似乎从 2 开始(售出的第一张票是 2)就您所见,有什么理由发生这种情况吗?
  • 去掉数组和列表会去掉IndexOutOfRangeException,使用TryParse会去掉NumberFormatException。请记住,列表就是字面意思,想象一下把它写在一张纸上。现在你说的是列表的size,或第一个元素。如果您出售 2 张门票,您的代码 seatsBooked.Add(firstClassSeat); 所做的就是将 2 添加到列表中。列表 size 将为 1,列表中唯一的 element 将是数字 2。
  • 我理解其中的逻辑,但我不确定使用布尔数组跟踪预订座位所需的语法?
  • 如果您有兴趣跟踪个人席位(您目前没有这样做),您只需要bools 数组。如果您只需要跟踪 数量 个座位,那么简单的 int 会容易得多。
【解决方案2】:

我会以非常不同的方式做这件事。您应该有一个座位类,其中包含一个用于预订的布尔值并对其进行迭代,而不是随机排列的书籍,这些书籍可能会或可能不会链接到已预订座位的随机列表和已预订的座位数。这是一个小例子:

public class Seat
{
    public int SeatNo { get; set; }
    public bool FirstClass { get; set ; }
    public bool Booked { get; set; } // could actually be an instance of a booking info class including name and ticket id, etc.
}

public class Flight
{
    public List<Seat> Seats = new List<Seat>();
    private int _lastSeat = 0;
    public void AddSeats(int num, bool firstClass)
    {
        for (int i = 0; i < num; i++)
        {
            _lastSeat++;
            Seats.Add(new Seat { SeatNo = num, FirstClass = firstClass });
        }
    }

    public int BookNextAvailableSeat(bool firstClass)
    {
        foreach (Seat seat in Seats.AsQueryable().Where(x => x.FirstClass == firstClass)
        {
            if (!seat.Booked)
            {
                seat.Booked = true;
                return seat.SeatNo;
            }
        }
        return null;
    }
}

那么你的:

case 1:
    int booking = flight.BookNextAvailableSeat(true);
    if (booking != null)
        Console.WriteLine("Your seat: {0}", booking);
    else
        Console.WriteLine("All seats for first class have been booked");
    Console.WriteLine("Please press enter to continue...");
    break;

当然,您需要使用以下方法实例化航班并添加 32 个座位:

Flight flight = new Flight();
flight.AddSeats(32, true);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-23
    • 2010-09-17
    • 2013-05-20
    相关资源
    最近更新 更多