我在C#中进行测验,并随机询问我的问题。问题是我只想在每种情况下去一次。我怎样才能做到这一点?
感谢您的回答。
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;
}
答案 0 :(得分:6)
创建问题列表
List<string> questions = new List<string>()
{
strQ1,strQ2,strQ3,strQ4,strQ5,strQ6,strQ7,strQ8,strQ9,strQ10
};
然后更改您的随机生成以从列表中找到问题
Random rdmNb = new Random();
int rdm1 = rdmNb.Next(0, questions.Count);
lblQuesttion.Text = questions[rdm1];
并删除列表中提出的问题
questions.RemoveAt(rdm1);
无需切换....
请务必在循环外声明Random变量,以驱动您选择下一个问题。如在这个例子中
// 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?
}
修改强>
在表单中声明并初始化具有全局范围的问题列表。
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.....
}
}
答案 1 :(得分:1)
你总能这样:
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()));
现在你只需要.Pop()
来自堆栈的问题,就像这样:
if (questionsStack.Count > 0)
{
lblQuesttion.Text = questionsStack.Pop();
}