首页 > 解决方案 > 尝试使用键输入重置部分程序

问题描述

很久以前,我为一个假日聚会制作了一个小程序。这个想法是每个人都有一个数字,我会运行这个程序并让随机数生成器选择一个数字。有号码的人会轮流去那里玩派对游戏。稍后再看它,我想用一个键输入刷新程序,比如(按 R 刷新数字)。我曾经不得不继续重新运行程序,是否有任何我可以输入的 C# 代码行允许这样做?我曾想过使用一个函数来完成这项工作,但我不知道该怎么做。这是代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace WhiteChristmas.Exe
{
    class Program
    {
         static void Main(string[] args)



        {

            {
             Console.ForegroundColor = ConsoleColor.Red;
            Console.WriteLine("Welcome to the WhiteChristmas random number Generator!!!");
            Console.ResetColor();
            Console.ForegroundColor = ConsoleColor.Green;
            Console.WriteLine("You where given a number when you walked in if your number is called then step up and play the game!");
            Console.ResetColor();

        }

        Random rnd = new Random();
        int dice = rnd.Next(1, 14);
        Console.ForegroundColor = ConsoleColor.Cyan;
        Console.WriteLine("The card that is picked is:" + dice);
        Console.ResetColor();

        Console.WriteLine("Press any key to Exit...");
        Console.ReadKey();

    }
}

}

标签: c#

解决方案


这可能是您问题的答案。基本上控制台应用程序会监听键 R 以及何时遇到正确的键。运行应该返回随机数的方法。为了使您的要求成为可能,您应该像这样修改代码。

   static void Main(string[] args)
    {
        while (Console.ReadKey(true).Key == ConsoleKey.R)
        {
            RandomNumber();            }
    }

    static void RandomNumber()
    {
        Random rnd = new Random();
        int dice = rnd.Next(1, 14);
        Console.ForegroundColor = ConsoleColor.Cyan;
        Console.WriteLine("The card that is picked is:" + dice);
        Console.ResetColor();

    }

推荐阅读