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

时间:2013-05-23 14:17:00

标签: c#

我正在开展一个测验项目,该项目还允许用户添加新问题。

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

7 个答案:

答案 0 :(得分:1)

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

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

您可以考虑申请Question课程。这将包含问题的string Text成员(因为我认为Question.Question很傻,Question.Text在阅读时更有意义)。由于你提到了 ArrayList(不是因为我认为这是最好的解决方案),你可以将其中一个作为成员包含所有可能的答案。

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

答案 1 :(得分:1)

我会创建一个包含问题,正确答案和可能答案列表的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);
    }
}

答案 2 :(得分:1)

根据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();
    }
}

答案 3 :(得分:0)

您应该将所有问题封装在一个类中。例如,创建一个名为Question的类。此类可以包含5个变量:String questionString answer1String answer2String answer3String answer4

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

使用Random课程随机选择一个问题并“混乱”4个问题。

答案 4 :(得分:0)

这是一种可行的方法:

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

只是将它改编为字符串数组而不是int数组

答案 5 :(得分:0)

洗牌可能是一个标准问题,但我想这会起作用:

// 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>。传入的对象不会发生变异。

答案 6 :(得分:0)

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

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