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

本文关键字:访问 字符串 随机 数组 列表 | 更新日期: 2023-09-27 18:15:06

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

我有一个数组列表,其中存储和检索问题以进行显示。数组列表中保存的每个对象包含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();
            }
        }
    }
}

这是类问题的代码

namespace quiz
{
    [Serializable()]
    public class Question : ISerializable
    {
        public String Quest;
        public String RightAnswer;
        public String WrongAnswer1;
        public String WrongAnswer2;
        public String WrongAnswer3;
        public Question()
        {
           Quest = null;
           RightAnswer=null;
           WrongAnswer1=null;
           WrongAnswer2=null;
           WrongAnswer3=null;
        }
        //serialization function
        public void GetObjectData(SerializationInfo info, StreamingContext context)
        {
            info.AddValue("Question", Quest);
            info.AddValue("Right Answer", RightAnswer);
            info.AddValue("WrongAnswer1",WrongAnswer1);
            info.AddValue("WrongAnswer2",WrongAnswer2);
            info.AddValue("WrongAnswer3",WrongAnswer3);
        }
        //deserializaton constructor
        public Question(SerializationInfo info, StreamingContext context)
        {
            Quest = (String)info.GetValue("Question", typeof(String));
            RightAnswer=(String)info.GetValue("Right Answer",typeof(String));
            WrongAnswer1=(String)info.GetValue("WrongAnswer1",typeof(String));
            WrongAnswer2=(String)info.GetValue("WrongAnswer2",typeof(String));
            WrongAnswer3=(String)info.GetValue("WrongAnswer3",typeof(String));
        }     
    }
}

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

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

// 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 radioButton_CheckedChanged(object sender, EventArgs e)
{
    RadioButton rb = (RadioButton)sender;
    Question q = questionList[index];
    //if checkbox is checked
    //displaying text in separate two lines on messagebox
    if (rb.Checked && q.RightAnswer == rb.Text)
    {
        // Move your code to another method
        // MessageBox.Show("Well Done" + Environment.NewLine + "You Are Right");
        UserSelectedCorrectAnswer();
    }
    else if (rb.Checked)
    {
        // They checked the radio button, but were wrong!
        // MessageBox.Show("Sorry" + Environment.NewLine + "You Are Wrong");
        UserSelectedWrongAnswer();
    }
}

从数组列表中选择一个随机字符串:

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

你可以考虑上Question课。这将包含一个string Text成员的问题(因为我认为问题。问题是愚蠢的,问题。文本在阅读时更有意义)。既然你提到了ArrayList(不是因为我认为这是最好的解决方案),你也可以有其中一个作为成员,它将包含所有潜在的答案。

创建问题时,可以显示Question.Text,然后使用上面的函数随机选择一个答案。然后在答案上使用RemoveAt(index),以确保您不会重复答案。

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

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);
    }
}

你应该把所有的问题封装在一个类中。例如,创建一个名为Question的类。这个类可以包含5个变量:String question, String answer1, String answer2, String answer3String answer4

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

使用Random类随机选择一个问题并对4个问题进行"洗牌"。

这里有一个可以工作的方法:

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;
}

把它改成string数组而不是int数组

洗牌可能是一个标准问题,但我想这将工作:

// 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];
  }
}

如果你没有IReadOnlyList<T>(。. NET 4.5),只使用IList<T>

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

 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;
            }
        }
    }