Vincent During Vincent During - 3 months ago 8
C# Question

How to make instances of a class unique each time in a loop

I need help with a console application I'm making. I'm making a application to use for studying. I want to be able to start it up, enter how many questions I want to have, enter question and answer for each question, use a looping method that will forever loop and ask those same questions over and over. Thought this would be really useful. But I have meet a problem on the way. I use a class to create instances for the questions and their respective answers, but I don't know how to make the instance name different for each question. Here's the code below

namespace glosor
{
class Program
{

static void Main(string[] args)
{
Console.WriteLine("Hello, please enter how many questions you would like to have on this reapeting test");
int numberofquestions = Convert.ToInt32(Console.ReadLine());
while(numberofquestions > 0)
{
Console.WriteLine(" what do you want question number " + numberofquestions + " to be?");

QuestionAndAnswer question = new QuestionAndAnswer(null,null);
question.answer = Console.ReadLine();
Console.WriteLine(" what do you want question number " + numberofquestions + "'s answer to be?");
question.answer = Console.ReadLine();
numberofquestions--;
QuestionAndAnswer.numberofquestions++;
}


}


class QuestionAndAnswer{
public string question;
public string answer;
public static int numberofquestions;
public QuestionAndAnswer(string _question,string _answer)
{
question = _question;
answer = _answer;


}
}


}
}

Answer

You need to store a collection of QuestionAndAnswer separately.

When you do this within the loop.

QuestionAndAnswer question = new QuestionAndAnswer(null,null);

The variable is scoped to a single iteration of the loop, so once the loop repeats you loose that previous information.

Create a collection before the loop, within the loop add your QuestionAndAnswer objects into the List. The information within the List will then be available after the loop has completed.

List<QuestionAndAnswer> allQuestionAndAnswers = new List<QuestionAndAnswer>();

while(numberofquestions > 0)
{
    ...other code here
    QuestionAndAnswer question = new QuestionAndAnswer("The question", "The answer");
    allQuestionAndAnswers.Add(question);
}

Additionally, you are setting question.answer twice, I'm guessing the first one should be question.question.

QuestionAndAnswer question = new QuestionAndAnswer(null,null);
question.answer = Console.ReadLine(); //Once here
Console.WriteLine(" what do you want question number " + numberofquestions + "'s answer to be?");
question.answer = Console.ReadLine(); //And again a second time
Comments