C# 从数组列表中随机访问字符串

C# 从数组列表中随机访问字符串,c#,C#,我正在做一个测验项目,它也允许用户添加新的问题 我有一个数组列表,其中存储和检索问题以供显示。保存在数组列表中的每个对象包含5个字符串 问题: 正确答案 错误答案1 错误答案2 错误答案3 如何从阵列列表中随机选择要在屏幕上显示的对象?我如何将这4个答案(单选按钮)混洗,使正确的答案每次出现在不同的位置 namespace quiz { public partial class Quiz : Form { private ArrayList Quest

我正在做一个测验项目,它也允许用户添加新的问题

我有一个数组列表,其中存储和检索问题以供显示。保存在数组列表中的每个对象包含5个字符串

  • 问题:
  • 正确答案
  • 错误答案1
  • 错误答案2
  • 错误答案3
如何从阵列列表中随机选择要在屏幕上显示的对象?我如何将这4个答案(单选按钮)混洗,使正确的答案每次出现在不同的位置

    namespace quiz
{
    public partial class Quiz : Form
    {
        private ArrayList Questionslist;

        public Quiz(ArrayList list)
        {
            InitializeComponent();
            Questionslist = list;
        }

        int index = 0;
        private void Quiz_Load(object sender, EventArgs e)
        {
            //creating an object of class Question and copying the object at index1 from arraylist into it  
            Question q = (Question)Questionslist[index];
            //to display the contents
            lblQs.Text = q.Quest;
            radioButtonA1.Text = q.RightAnswer;
            radioButtonA2.Text = q.WrongAnswer1;
            radioButtonA3.Text = q.WrongAnswer2;
            radioButtonA4.Text = q.WrongAnswer3;            
        }

        private int Score = 0;

        private void radioButtonA1_CheckedChanged(object sender, EventArgs e)
        {
            //if checkbox is checked
            //displaying text in separate two lines on messagebox
            if (radioButtonA1.Checked == true)
            {
                MessageBox.Show("Well Done" + Environment.NewLine + "You Are Right");
                Score++;
                index++;

                if (index < Questionslist.Count)
                {
                    radioButtonA1.Checked = false;
                    radioButtonA2.Checked = false;
                    radioButtonA3.Checked = false;
                    radioButtonA4.Checked = false;
                    Quiz_Load(sender, e);
                }
                else
                {
                    index--;
                    MessageBox.Show("Quiz Finished" + Environment.NewLine + "your Score is" + Score);
                    Close();
                }
            }
        }

        private void radioButtonA2_CheckedChanged(object sender, EventArgs e)
        {
            if (radioButtonA2.Checked == true)
            {
                MessageBox.Show("Sorry" + Environment.NewLine + "You Are Wrong");
                Close();
            }
        }

        private void radioButtonA3_CheckedChanged(object sender, EventArgs e)
        {
            if (radioButtonA3.Checked == true)
            {
                MessageBox.Show("Sorry" + Environment.NewLine + "You Are Wrong");
                Close();
            }
        }

        private void radioButtonA4_CheckedChanged(object sender, EventArgs e)
        {
            if (radioButtonA4.Checked == true)
            {
                MessageBox.Show("Sorry" + Environment.NewLine + "You Are Wrong");
                Close();
            }
        }
    }
}

你应该把所有的问题封装在一节课上。例如,创建一个名为
Question
的类。此类可以包含5个变量:
字符串问题
字符串回答1
字符串回答2
字符串回答3
字符串回答4

将所有问题保存在数据库中,或从文件中读取并在程序开始时加载


使用本课程随机选择一个问题,并“洗牌”这4个问题

从ArrayList中选择一个随机字符串:

string randomPick(ArrayList strings)
{
    return strings[random.Next(strings.Length)];
}

您可以考虑使用<代码>问题< /代码>类。这将包含问题的

字符串文本
成员(因为我认为question.question很傻,question.Text在阅读时更有意义)。既然您提到了一个
ArrayList
(并不是因为我认为它是最好的解决方案),您也可以将其中一个作为成员,它将包含所有可能的答案


创建问题时,可以显示
question.Text
,然后使用上述功能随机选择答案。然后在答案上使用
RemoveAt(index)
,以确保不会重复答案。

以下是一种有效的方法:

public List<string> Randomize(string[] numbers)
{
    List<string> randomized = new List<string>();
    List<string> original = new List<string>(numbers);
    Random r = new Random();
    while (original.Count > 0) {
        int index = r.Next(original.Count);
        randomized.Add(original[index]);
        original.RemoveAt(index);
    }

return randomized;
}
// Warning: Not a thread-safe type.
// Will be corrupted if application is multi-threaded.
static readonly Random randomNumberGenerator = new Random();


// Returns a new sequence whose elements are
// the elements of 'inputListOrArray' in random order
public static IEnumerable<T> Shuffle<T>(IReadOnlyList<T> inputListOrArray)
{
  return GetPermutation(inputListOrArray.Count).Select(x => inputListOrArray[x]);
}
static IEnumerable<int> GetPermutation(int n)
{
  var list = Enumerable.Range(0, n).ToArray();
  for (int idx = 0; idx < n; ++idx)
  {
    int swapWith = randomNumberGenerator.Next(idx, n);
    yield return list[swapWith];
    list[swapWith] = list[idx];
  }
}
公共列表随机化(字符串[]数字)
{
列表随机化=新列表();
原始列表=新列表(编号);
随机r=新随机();
而(原始计数>0){
int index=r.Next(原始计数);
随机。添加(原始[索引]);
原始。删除(索引);
}
回归随机化;
}

只需将其调整为字符串数组而不是int数组

我将创建一个
问题
类,其中包含问题、正确答案和可能答案列表,并具有以随机顺序返回可能答案并将猜测与正确答案进行比较的方法。它可能看起来像这样:

class Question
{
    String question;
    String rightAnswer;
    List<String> possibleAnswers = new ArrayList<String>();

    public Question(String question, String answer, List<String> possibleAnswers)
    {
      this.question = question;
      this.rightAnswer = answer;
      this.possibleAnswers.addAll(possibleAnswers);
      this.possibleAnswers.add(this.rightAnswer);
    }

    public List<String> getAnswers()
    {
        Collections.shuffle(possibleAnswers);
        return possibleAnswers;
    }

    public boolean isCorrect(String answer)
    {
      return answer.equals(correctAnswer);
    }
}
课堂提问
{
字符串问题;
字符串右键回答;
List-possibleAnswers=new-ArrayList();
公开问题(字符串问题、字符串答案、列出可能的答案)
{
这个问题=问题;
this.rightAnswer=答案;
this.possibleAnswers.addAll(possibleAnswers);
this.possibleAnswers.add(this.rightAnswer);
}
公共列表getAnswers()
{
集合。洗牌(可能的回答);
返回可能的答案;
}
公共布尔值isCorrect(字符串应答)
{
返回答案。等于(正确答案);
}
}

洗牌可能是一个标准问题,但我想这会奏效:

public List<string> Randomize(string[] numbers)
{
    List<string> randomized = new List<string>();
    List<string> original = new List<string>(numbers);
    Random r = new Random();
    while (original.Count > 0) {
        int index = r.Next(original.Count);
        randomized.Add(original[index]);
        original.RemoveAt(index);
    }

return randomized;
}
// Warning: Not a thread-safe type.
// Will be corrupted if application is multi-threaded.
static readonly Random randomNumberGenerator = new Random();


// Returns a new sequence whose elements are
// the elements of 'inputListOrArray' in random order
public static IEnumerable<T> Shuffle<T>(IReadOnlyList<T> inputListOrArray)
{
  return GetPermutation(inputListOrArray.Count).Select(x => inputListOrArray[x]);
}
static IEnumerable<int> GetPermutation(int n)
{
  var list = Enumerable.Range(0, n).ToArray();
  for (int idx = 0; idx < n; ++idx)
  {
    int swapWith = randomNumberGenerator.Next(idx, n);
    yield return list[swapWith];
    list[swapWith] = list[idx];
  }
}
//警告:不是线程安全类型。
//如果应用程序是多线程的,则将被损坏。
静态只读随机数生成器=新随机数();
//返回一个新序列,其元素为
//“inputListOrArray”元素的随机顺序
公共静态IEnumerable Shuffle(IReadOnlyList inputListOrArray)
{
返回GetPermutation(inputListOrArray.Count)。选择(x=>inputListOrArray[x]);
}
静态IEnumerable GetPermutation(int n)
{
var list=Enumerable.Range(0,n).ToArray();
对于(int idx=0;idx

如果没有
IReadOnlyList
(.NET4.5),只需使用
IList
。传入对象不会发生变异。

根据
文本属性,您知道哪一个是“正确”答案。一种方法是将答案存储在一个数组中,并在将数组分配给单选按钮之前将其洗牌:

// You're going to make questionList a List<Question> because if you like
// Right answers you know that ArrayList is Wrong.
Question q = questionList[index];

// You should move this next bit to the Question class
string[] answers = new string[]
    {
        q.RightAnswer,
        q.WrongAnswer1,
        q.WrongAnswer2,
        q.WrongAnswer3
    };

// Using the Fisher-Yates shuffle from:
// http://stackoverflow.com/questions/273313/randomize-a-listt-in-c-sharp
Shuffle(answers);

// Ideally: question.GetShuffledAnswers()

radioButtonA1.Text = answers[0];
radioButtonA2.Text = answers[1];
radioButtonA3.Text = answers[2];
radioButtonA4.Text = answers[3];

感谢所有回答我问题的人,我就是这样做的

 private void Quiz_Load(object sender, EventArgs e)
    {
        displayQs();
    }

    private void displayQs()
    {
            Random _random = new Random();
            int z = _random.Next(Questions.Count);
            Question q = (Question)Questions[z];
            Qslbl.Text = q.Quest;
            DisplayAns(q, _random);
    }

    private void DisplayAns(Question q, Random _random)
    {
        int j = 0;
        int[] array = new int[4];
        for (int i = 0; j <= 3; i++)
        {
            int x = _random.Next(4);
            x++;
            if (array.Contains(x))
            {
                continue;
            }
            else
            {
                array[j] = x;
                j++;
                string answer = null;
                if (j == 1)
                    answer = q.RightAnswer;
                else if (j == 2)
                    answer = q.WrongAnswer1;
                else if (j == 3)
                    answer = q.WrongAnswer2;
                else if (j == 4)
                    answer = q.WrongAnswer3;

                if (x == 1)
                    radioButton1.Text = answer;
                else if (x == 2)
                    radioButton2.Text = answer;
                else if (x == 3)
                    radioButton3.Text = answer;
                else if (x == 4)
                    radioButton4.Text = answer;
            }
        }
    }
private void测验加载(对象发送方,事件参数e)
{
displayQs();
}
私有void displayQs()
{
随机_Random=新随机();
intz=_random.Next(问题数);
问题q=(问题)问题[z];
Qslbl.Text=q.Quest;
显示器(q,u随机);
}
私有无效显示(问题q,随机\u随机)
{
int j=0;
int[]数组=新的int[4];

对于(int i=0;j)您当前的代码是什么样子的?您是否考虑过寻找
随机的
?确实没有理由再使用
ArrayList
,您应该在一个能够更好地描述数据模型的类中,用相关的答案来组织您的问题。