C#从列表中返回随机字符串

时间:2019-05-04 15:27:27

标签: c# random

我写出了一个列表,上面有问题的答案。我想使用GetAnswer()方法以字符串形式返回当前答案。

我遇到的问题是我无法获得选择打印的随机答案。

namespace Magic8Ball_Logic
{

public class Magic8Ball
{
    private List<string> _answers;
    private int _currentIndex;
    public Magic8Ball()
    {
        _answers = new List<string>();
        _answers.Add("It is certain.");
        _answers.Add("It is decidedly so.");
        _answers.Add("Without a doubt.");
    }

    public Magic8Ball(List<string> answers)
    {
        //I won't use the default. Use the ones passed in.
        _answers = answers;
    }

    public void Shake()
    {
        //picking the index of the answer to show the user
        Random r = new Random();
        int index = r.Next(_answers.Count);
        string randomString = _answers[index];
    }

    public string GetAnswer()
    {
        //using the index picked by shake to return the answer
        return randomString;
    }

3 个答案:

答案 0 :(得分:0)

使用原始代码:

public void Shake()
{
    //picking the index of the answer to show the user
    Random r = new Random();
    _currentIndex = r.Next(_answers.Count);
}

public string GetAnswer()
{
    //using the index picked by shake to return the answer
    return _answers[_currentIndex];
}

您可能需要将您的static设为随机。您还可以参考其他线程。

答案 1 :(得分:0)

告诉我,如果您听不懂。

   public Form1()

    {
        InitializeComponent();
        _answers.Add("It is certain.");
        _answers.Add("It is decidedly so.");
        _answers.Add("Without a doubt.");
    }

    List<string> _answers = new List<string>();

    private void BtnRandom_Click(object sender, EventArgs e)
    {
        MessageBox.Show(GetAnswer());

    }
    string GetAnswer()
    {
        Random rnd = new Random();
        int i = 0;
        int _rnd = rnd.Next(_answers.Count);
        foreach (string answer in _answers)
        {
            if (i == _rnd)
            {
                return answer;
            }
            i++;
        }

        return "";
    }
}

答案 2 :(得分:-1)

您可以通过使用系统附带的Random类来做到这一点。 确保代码顶部有using System;。如果要避免在代码顶部添加此行,则可以在每次看到“随机”一词之前添加System.

Random rnd = new Random();
return _asnswers[rnd.Next(0, _answers.Count);

通过这种方式,请尽量避免在开头使用'_'变量,因为它用于其他类型的变量,例如:

using _StartWith = System.File;

将变量命名为“答案”(首选)或“答案”。 该代码将100%起作用,但这只是当其他人查看您的代码时,他们就会知道什么变量是什么类型。

此外,我假设您想将答案随机排列,所以我也将为您提供帮助:

Random rnd = new Random();
for (int i = _answers.Count - 1; i >= 0; i++)
{
    _answers.Add(    // Add the random removed answer
    _answers.Remove( // Removes the random answer
    rnd.Next(0, i)));// Randomizes a random answer in a range of 0 to the number of answers that didn't get picked before.
}

祝你好运! 告诉我是否有帮助:)