繁体   English   中英

C#需要建立一个循环来拒绝无效的用户输入(低于5的1 /以下)我该怎么做? 编码新手,制作电影院入门应用程序

[英]C# Need to set up a loop to reject invalid user input (below 1/ above 5) How can I do that? New to coding, making cinema entry app

namespace ConsoleApplication2
{
  class Program
  {
    static void Main()
    {
        Console.WriteLine("Welcome to our Multiplex");



        Console.WriteLine("We are presently Showing:");
        Console.WriteLine("1.Legend");
        Console.WriteLine("2.Macbeth");
        Console.WriteLine("3.Everest");
        Console.WriteLine("4.A Walk In the Woods");
        Console.WriteLine("5.Hotel Transylvania");

        Console.WriteLine("Enter the number of the film you wish to see?");

        {


            string moviestring = Console.ReadLine();

            int movie = int.Parse(moviestring);

这是我可以针对您的情况建议的解决方案:

    static void Main(){
        bool flag0 = true; //initialize tracking bool value to exit loop when needed
        int result;
        Console.WriteLine("Welcome to our Multiplex");

        Console.WriteLine("We are presently Showing:");
        Console.WriteLine("1.Legend");
        Console.WriteLine("2.Macbeth");
        Console.WriteLine("3.Everest");
        Console.WriteLine("4.A Walk In the Woods");
        Console.WriteLine("5.Hotel Transylvania");


        do //do while loop suits this case best as it does check the value on the end
        {
            Console.WriteLine("Enter the number of the film you wish to see?");
            string moviestring = Console.ReadLine();

            int.TryParse(moviestring, out result); //does try-catch check so it wont crash on the run-time

            if (result <= 5 && result >= 1) //logical check if value is correct
                flag0 = false; //exits the loop
            //do true logic....
            else
                Console.WriteLine("Incorrect value. Try again.");
            //do false logic

        } while (flag0);
   }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM