DanyDC
DanyDC

Reputation: 73

How can I go only once in a switch case?

I make a quiz in C# and my questions are randomly asked with a random number. The problem is I just want to go once in each cases. How can I achieve this?

Thanks for your answers.

Random rdmNb = new Random();
int rdm1 = rdmNb.Next(1, 11);

switch (rdm1)
{
    case 1:           
        lblQuesttion.Text = strQ1;
        break;
    case 2:
        lblQuesttion.Text = strQ2;
        break;
    case 3:
        lblQuesttion.Text = strQ3;
        break;
    case 4:
        lblQuesttion.Text = strQ4;
        break;
    case 5:
        lblQuesttion.Text = strQ5;
        break;
    case 6:
        lblQuesttion.Text = strQ6;
        break;
    case 7:
        lblQuesttion.Text = strQ7;
        break;
    case 8:
        lblQuesttion.Text = strQ8;
        break;
    case 9:
        lblQuesttion.Text = strQ9;
        break;
    case 10:
        lblQuesttion.Text = strQ10;
        break;
}

Upvotes: 1

Views: 1290

Answers (2)

Enigmativity
Enigmativity

Reputation: 117029

You could always to this:

List<string> questions = new List<string>()
{
   strQ1,strQ2,strQ3,strQ4,strQ5,strQ6,strQ7,strQ8,strQ9,strQ10
};

var rnd = new Random();
var questionsStack = new Stack<string>(questions.OrderBy(x => rnd.Next()));

Now you just .Pop() questions from the stack as you need them, like this:

if (questionsStack.Count > 0)
{
    lblQuesttion.Text = questionsStack.Pop();
}

Upvotes: 1

Steve
Steve

Reputation: 216253

Create a list of your questions

List<string> questions = new List<string>()
{
   strQ1,strQ2,strQ3,strQ4,strQ5,strQ6,strQ7,strQ8,strQ9,strQ10
};

Then change your random generation to find a question from the list

Random rdmNb = new Random();
int rdm1 = rdmNb.Next(0, questions.Count);

lblQuesttion.Text = questions[rdm1];

and remove the question asked from the list

questions.RemoveAt(rdm1);

no switch required....

Be sure to declare the Random variable outside the loop that drives your selection of the next question. As in this example

// Declare globally the random generator, not inside the question loop
Random rdmNb = new Random();

while (questions.Count > 0)
{
    int rdm1 = rdmNb.Next(0, questions.Count);
    string curQuestion = questions[rdm1];
    questions.RemoveAt(rdm1);

    lblQuestion.Text = curQuestion;

    ... ?code to handle the user input?
}

EDIT
Declaring and initializing your question list with global scope inside the form.

public class MyForm : Form
{
     // Declaration at global level
     List<string> questions;

     public MyForm()
     {
         InitializeComponent();
         LoadQuestions();
     }

     private void LoadQuestions()
     {
        questions = new List<string>()
        {
            strQ1,strQ2,strQ3,strQ4,strQ5,strQ6,strQ7,strQ8,strQ9,strQ10
        };

        // In future you could change this method to load your questions
        // from a file or a database.....
     }

}

Upvotes: 6

Related Questions