从Array C#Console输出随机字符串

时间:2018-06-10 01:39:19

标签: c# visual-studio console-application

string[] aNames = new string[10] { "Ronaldo", "Messi", "Aguero", "Dembele", "Reus", "Mbappe", "Sane", "Sterling", "Ibrahimovic", "Alaba" };

这是我的阵列。我需要从这个数组输出一个随机字符串到控制台,然后一旦输出名称,用户必须输入要赢的第一个名字,如果他们弄错了他们就输了,有什么帮助吗?

1 个答案:

答案 0 :(得分:1)

using System;

public class Program
{
    private static string[] aNames = new string[10] { "Ronaldo", "Messi", "Aguero", "Dembele", "Reus", "Mbappe", "Sane", "Sterling", "Ibrahimovic", "Alaba" };
    private static string[] FirstNames = new string[10] {"Cristiano", "Lionel", "Sergio", "Ousmane", "Marco", "Kylian", "Leroy", "Raheem", "Zlatan", "David" };
    private static int randomIndex = -1;
    private static String UserInput = "";

    public static void Main()
    {
        ShowQuestion();
    }


    private static void ShowQuestion()
    {
        Random rd = new Random();
        randomIndex = rd.Next(0, aNames.Length);
        Console.WriteLine("Enter the First Name of "+aNames[randomIndex]);
        GetUserInput();
    }
    private static void GetUserInput()
    {
        UserInput = Console.ReadLine();
        Console.WriteLine("You Entered : "+UserInput);
        CheckTheAnswer();       
    }

    private static void CheckTheAnswer()
    {
        if (string.Equals(UserInput, FirstNames[randomIndex], StringComparison.OrdinalIgnoreCase))
            {
                Console.WriteLine("You Win");
                RePlay();

            }else{
                Console.WriteLine("You Lose");
                RePlay();
            }
    }

    private static void RePlay()
    {
        Console.WriteLine("To reply enter Y else N");
        UserInput = Console.ReadLine();
        switch(UserInput)
        {
            case "Y":
            case "y":
                ShowQuestion();
            break;
            default:
              System.Environment.Exit(1);
            break;
        }

    }

}

试试这个,Random.Next Method

了解更多信息