当用户输入字母而不是数字时

时间:2016-06-09 08:05:28

标签: c#

int anotherShowing = 1; // Variable for the user to select another showing.

        while (anotherShowing == 1) // While loop so the program keeps going until the user has selected a film.
        {
            Console.Write("Select A Showing: "); // Outputs "Select A showing" to the console window.
            int showingSelect = Console.ReadLine(); // Variable for the user to input a showing number and converts it to a int.
            int.TryParse(anotherShowing, out showingSelect);
            if (showingSelect == 0)
            {
                Console.Write("please input valid number");
            }
            Showing Selection; // Variable so Selection can be linked to the Showing class to be used for the ShowingSelect.
            Selection = list[showingSelect - 1]; // Recongnizes the showing number the user inputs.
            Console.Write("Number of Tickets: "); // Oupts "Number of Tickets" to the console window.
            int numberOfTickets = Convert.ToInt32(Console.ReadLine()); // Variable for the user to input how many tickets they want and converts it to a int. 
            Booking Booking1; // Variable so Booking1 can be linked to the Booking class to be used for the NumberOfTickets.
            if (Selection.getSeatsAvailable() > numberOfTickets) // If statement so the program knows if there are enough tickets left.
            {
                Booking1 = new Booking(Selection, numberOfTickets); // If enough tickets program will make a new booking (Booking1) which includes the Selection and the NumberOfTickets.
                Selection.updateSeatsAvailable(numberOfTickets); // Updates how many tickets are available for that showing.
                Console.Clear(); // Clears the console window.
                Console.Write(Booking1.toString()); // Outputs the Booking1 variable, including the Film selected and the number of tickets.
                break; // Stops the program.
            }
            else // If there aren't enough tickets.
            {
                Console.WriteLine("Showing Full"); // Outputs "Showing Full" to the console window.
                Console.WriteLine("Select another showing"); // Outputs "Select another showing" to the console window.
            }

            Console.Write("Press 1 Then Return To Select Another Showing\n"); // Outputs to the console window.
            anotherShowing = Convert.ToInt32(Console.ReadLine()); // Allows the user to input 1 to select another showing and converts it to a int.
        }

        Console.Read();
    }

我正在尝试为作业编写一个简单的电影节目。 我看了一些例子,告诉用户如果输入一个数字就告诉用户输入一个字母而不是数字。 我添加了TryParse但是有一些错误:

errors

请帮助代码, 感谢

1 个答案:

答案 0 :(得分:2)

Console.ReadLine()返回string 而不是 int值。

所以我们应该这样做。

int showingSelect;

if(int.TryParse(Console.ReadLine(), out showingSelect))
{
    // valid showingSelect
}
else
{
    // invalid input  
    Console.Write("please input valid number");
    continue;  // continue loop. 
}