简体   繁体   English

执行循环,直到用户按下特定按钮

[英]Execute a loop until user presses a specific button

I am trying to create a multi functional program. 我正在尝试创建一个多功能程序。 For one part, an array is filled with random numbers. 一方面,一个数组填充有随机数。 The user then enters in a number and the program returns which positions the number appears in the array. 然后,用户输入一个数字,程序返回该数字出现在数组中的哪个位置。 It also returns the number of times the number appears in the array. 它还返回该数字出现在数组中的次数。

However it only does this once and after that it ends the program. 但是,它仅执行一次,然后结束程序。 I want it to prompt the user to enter in a number to search until the user presses a button, let's say 'P' for example. 我希望它提示用户输入要搜索的数字,直到用户按下按钮为止,例如说“ P”。 Once the user presses 'P' after the results are shown, the program should close. 结果显示后,一旦用户按“ P”,程序应关闭。 Any tips into what methods or functionality I should be using? 关于应使用哪种方法或功能的任何提示?

Here is a broken down version of my code. 这是我的代码的细分版本。

Console.Write("Now enter a number to compare: ");
int c = Convert.ToInt32(Console.ReadLine());

for (int j = 0; j < arr.Length; j++)
{
    if (arr[j] == c)
    {
        pos.Add(j);
    }
}          

if (pos.Count == 0)
{
    Console.WriteLine("Sorry this number does not match");
}
else
{
   Console.WriteLine("The number {0} appears {1} time(s)",c,pos.Count);
}

Console.ReadLine();

this should give you a little head start 这应该给您一些入门

you have to use a loop around your code and check for a keyword to exit 您必须在代码周围使用循环并检查要退出的关键字

class Program
{
    static void Main(string[] args)
    {
        var arr = new int[50];
        var pos = new List<int>();
        string result;
        do
        {
            Console.Write("Now enter a number to compare: ");
            result = Console.ReadLine();

            int c;

            if (int.TryParse(result, out c))
            {
                for (int j = 0; j < arr.Length; j++)
                {
                    if (arr[j] == c)
                    {
                        pos.Add(j);
                    }
                }

                if (pos.Count == 0)
                {
                    Console.WriteLine("Sorry this number does not match");
                }
                else
                {
                    Console.WriteLine("The number {0} appears {1} time(s)", c, pos.Count);
                }
            }


        } while (result != "exit");
    }
}

I am going to provide another approach, didn't test the code below though. 我将提供另一种方法,但是没有测试下面的代码。

class Program
{

    //declare your class variables here
    //so that you can access them from the methods and do your operations
    bool Up=true;

    static void Main(string[] args)
    {
        Console.WriteLine("Program started.");

        ThreadPool.QueueUserWorkItem(ConsoleCommands);
        while (Up)
        {
            Thread.Sleep(2000);
        }
        Console.WriteLine("Program ended.");
    }

    private static void ConsoleCommands(object dummy)
    {
        while (Up)
        {
            string cmd = ConsoleReceiver().ToLower();
            switch (cmd)
            {
                case "exit":
                    Up=false;
                    break;
                //implement more cases here and fill the rest of your business
                //example:
                case "1":
                    if (pos.Count == Int32.Parse(cmd))//just a dummy business
                    {
                        Console.WriteLine("Sorry this number does not match");
                    }
                    else//another dummy business
                    {
                        Console.WriteLine("Sth...");
                    }
                    break;
                default:
                    Console.WriteLine("Unrecognized command");
                    break;
            }//or forget about switch and use if-else stements instead.
        }
    }

    private static string ConsoleReceiver()
    {
        Console.WriteLine("#cmd:");
        return Console.ReadLine();
    }
}

If you want to explicitly read single keys strokes... 如果要显式读取单键笔触...

ConsoleKeyInfo keyInfo;
do {
    Console.Write("Enter a number to compare; press the 'p' key to quit: ");
    keyInfo = Console.ReadKey(false);

    int c;
    if (Int32.TryParse(keyInfo.KeyChar.ToString(), out c))
    {    
        for (int j = 0; j < arr.Length; j++)
        {
            if (arr[j] == c)
            {
                pos.Add(j);
            }
        }          

        if (pos.Count == 0)
        {
            Console.WriteLine("Sorry this number does not match");
        }
        else
        {
           Console.WriteLine("The number {0} appears {1} time(s)",c,pos.Count);
        }
} while (keyInfo.Key != ConsoleKey.P)

Otherwise you can get creative with combinations of what @Fredou and I have posted. 否则,您可以结合@Fredou和我发布的内容来发挥创意。

Try this :) 尝试这个 :)

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            start:
            string tryagain;


           //All of your Code Goes here


            tryagain = Console.ReadLine();
            if (tryagain != "p")
            {
            goto start;    
            }

            else
            {
                Environment.Exit(0);
            }


        }
    }
}

暂无
暂无

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

相关问题 有没有一种方法可以禁止在Winforms(c#)之外单击,直到用户按下关闭按钮? - Is there a way to disallow clicking outside of winforms (c#) until user presses close button? Unity - 用户按下特定对象(按钮),这反过来增加或减少他们的分数 - Unity - User presses a specific object (a button) which in turn increases or decreases their score 当用户按下删除按钮时删除一行 - Deleting a row when the user presses delete button C#循环过程直到用户按下一个键 - C# Looping A Process Over And Over Until A User Presses A Key 用户按下网页返回时如何执行事件 - How to execute event when user presses return on web page 当用户在Xamarin Forms上按下按钮时,显示按钮列表 - Display a list of Buttons when user presses a Button on Xamarin Forms 当用户按下MessageBox中的按钮时,如何播放声音? - How can I play a sound when a user presses a button in a MessageBox? 如果用户在 Xaml 中按下“完成交付”,如何隐藏“导航”按钮? - How to hide the "Navigate" button if the user presses the "Complete Delivery" in Xaml? 当表单请求导致文件下载时,如何在表单请求完成之前阻止按下按钮 - How do I prevent button presses until form request is completed when form request causes a file download 如何为 Switch 语句创建循环,直到用户在 C# 中键入特定单词为止 - How to Create a Loop for a Switch Statement That Repeats Until the User Types a Specific Word In C#
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM