簡體   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