用户输入数组,然后将其与随机数进行比较



我正在尝试制作经典的彩票样式代码,其中目的是让用户选择十个数字要播放,然后将这些数字与随机生成的数字进行比较。

到目前为止,我得到了这个:

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("Hello and Welcome to the Programming Lottery!"); //Just greetings and instructions.
        Console.WriteLine("You'll now get to choose ten different numbers to play with. ");
        Console.WriteLine("Go ahead and type them in.");
        int[] lotteri = new int[10]; //Array to catch ten numbers input.
        for (int i=0; i<lotteri.Length; i++)
            lotteri[i] = int.Parse(Console.ReadLine());
        Console.WriteLine("Very good! Now we'll see if you won anything!");
        Random randomNumber = new Random(1-100);        
        Console.ReadKey();
    }
}

,就我而言,我认为数组正在做应该做的事情(在继续前进之前收集用户输入十次)。

现在对我的主要问题是,我希望该程序将数组中的这些数字与随机选择的数字进行比较,并且如果这十个用户输入数字中的任何一个与随机生成的数字匹配,以告诉用户他们''VE获胜(或者如果没有,他们输了)。我似乎无法使它起作用!

次要问题,但是我正在尝试学习的方法更好,因此,如果有人在方法中使用阵列,然后将其转到主要,那也将非常感谢!

只需用以下方式替换此行Random randomNumber = new Random(1-100);

Random rnd = new Random();//Instanciate a Random object
int randomNumber = rnd.Next(1, 101);//Generate your Random number in range [[1,100]]

然后

经验解决方案(eack foreach)

foreach (var a in lotteri)
{
    if (a == randomNumber)
    {
        //Handle if the user got the number
        break;
    }
}

解决方案2(for each)

if (lotteri.Any(x => x == randomNumber))
    //Handle if the user got the number

解决方案3(使用包含)

if (lotteri.Contains(randomNumber))
    //Handle if the user got the number

编辑:添加了建议的解决方案并增加了Next()

的范围

程序如下:

    static void Main(string[] args)
    {
        try
        {
            Console.WriteLine("Hello and Welcome to the Programming Lottery!"); //Just greetings and instructions.
            Console.WriteLine("You'll now get to choose ten different numbers to play with. ");
            Console.WriteLine("Go ahead and type them in.");
            int[] lotteri = new int[10]; //Array to catch ten numbers input.
            for (int i = 0; i < lotteri.Length; i++)
            {
                lotteri[i] = int.Parse(Console.ReadLine());
            }
            Console.WriteLine("Very good! Now we'll see if you won anything!");
            Random rnd = new Random();
            int rnumber = rnd.Next(1, 100);
            bool isWin = false;
            isWin = lotteri.Contains(rnumber);
            Console.WriteLine("Lottery number is::" + rnumber);
            if (isWin)
            {
                Console.WriteLine("Very good! Now we'll see if you won anything!");
            }
            else
            {
                Console.WriteLine("Sorry...Better luck next time!!!");
            }
            Console.ReadKey();
        }
        catch (FormatException ex)
        {
            Console.WriteLine("Only number are allowed.");
        }
        catch
        {
            Console.WriteLine("Something went wrong.");
        }
        Console.ReadKey();
    }

最新更新