1

I am writing a C# program to display a test of questions. The test has 10 questions. But the program doesn't want to follow the same algorithm if I select a new quiz with the help of

   private void newToolStripMenuItem_Click (object sender, EventArgs e) 

The quiz doesn't stop after 10 questions.It goes on, it repeats the questions and at a certain number of questions it blocks.

I stepped through the code,and I saw:

  • When I resolve the quiz for the first time:questions.Count=10;
  • When I resolve it for the second time: questions.Count=20;
  • when I resolve it for the third time: questions.Count=30;

Would you like to tell me how can I have questions.Count=10 for every quiz, please ?

Here is my code:

public partial class Form3 : Form
{
    int nr;
    Collection<question> questions = new Collection<question>();

    public class question
    {
        public bool displayed = false;
        public string text;
    }


    //when I press a button from MenuStrip my quiz begin
    private void newToolStripMenuItem_Click(object sender, EventArgs e)
    {
        nr = 1;
        button1.Enabled = true;//it's the next_question button

        StreamReader sr = new StreamReader("quiz.txt");
        while (!sr.EndOfStream)
        {   
            question i = new question();
            questions.Add(i);
        }
        sr.Close();
        int x = r.Next(questions.Count);
        textBox1.Text = questionText;
        questions[x].displayed = true;
        current_question=x;
      }
}

I add that I tried to create

       Collection<question> questions = new Collection<question>()

for every quiz I resolve, putting this at the beginning of the

       private void newToolStripMenuItem_Click(object sender, EventArgs e) 

or at the end of my current quiz:

       if (nr >= questions.Count){ //here } 

None of these changes prevent the collection to increase with 10 questions. Thank you!

4

2 回答 2

2

添加一个 Clear 方法调用:

questions.Clear();

像这样:

private void newToolStripMenuItem_Click(object sender, EventArgs e)
{   nr = 1;
    button1.Enabled = true;//it's the next_question button
    questions.Clear();

    StreamReader sr = new StreamReader("quiz.txt");
    while (!sr.EndOfStream)
    {   
        question i = new question();
        questions.Add(i);
    }
    sr.Close();
    int x = r.Next(questions.Count);
    textBox1.Text = questionText;
    questions[x].displayed = true;
    current_question=x;

  }
于 2012-04-19T07:38:29.897 回答
1

questions = new Collection<question>();

newToolStripMenuItem_Click方法或使用的开始question.Clear();

不要Collection<question>在它前面包含类型,因为那样你正在创建一个新的局部变量。

于 2012-04-19T07:37:46.883 回答