我有一个项目,想要对随机问题和答案进行随机测验。我使用字典来做到这一点,并成功地提出了问题和答案,并随机显示了一个问题。
现在,我想为每个提出的问题添加具体答案。我想这也应该通过字典来完成,但是我不知道该如何做。
我已经制作了随机生成器,问题和答案(tkey和tvalue)
因此,现在我只需要添加一个部分,您可以为每个问题提供特定的答案,以及一种检测问题是对还是错的方法,这可以通过if和else语句来完成,但我的经验不足了解如何实现所有这些功能。
这就是我现在拥有的
class Program
{
static public void Main()
{
//maak een dictionary aan
Console.WriteLine("Quiz");
Dictionary<int, string> Questions = new Dictionary<int, string>();
//voeg vragen toe
//key koppelen aan vraag
Questions.Add(11, "Vraag1?");
Questions.Add(12, "Vraag2?");
Questions.Add(13, "Vraag3?");
Questions.Add(14, "Vraag4?");
Questions.Add(15, "Vraag5?");
Dictionary<int, string> answers = new Dictionary<int, string>();
List<int> keylist = new List<int>(); // string naar int converten
keylist = Questions.Keys.ToList();
Random rand = new Random(); //maak random aan
int countKeys = Questions.Keys.Count();
int randomIndex = rand.Next(0, countKeys);
Console.WriteLine(Questions.ElementAt(randomIndex).Key); //geef een random index en de gekoppelde key daaraan
string input = Console.ReadLine();
Console.WriteLine("You answered: " + input);
Console.ReadKey();
}
}
有人可以告诉我/帮助我为这些问题添加具体答案吗?
答案 0 :(得分:1)
您可以使用Dictionary<string, string>
将问题存储为键,将答案存储为值
然后,获取list of keys和shuffle,以最终遍历该列表。
在示例(fiddle to the below code)中:
private static Random rng = new Random();
public static void Shuffle<T>(this IList<T> list)
{
int n = list.Count;
while (n > 1)
{
n--;
int k = rng.Next(n + 1);
T value = list[k];
list[k] = list[n];
list[n] = value;
}
}
public static void Main(string[] args)
{
var quizz = new Dictionary<string, string>
{
{ "What is the answer to the Ultimate Question of Life, the Universe, and Everything ?", "42" },
{ "What is your name ?", "Sir Arthur, king of the Britons" },
{ "What is your quest ?", "To seek the Holy Grail" },
{ "What is the air-speed velocity of an unladen swallow?", "What do you mean ? An African or European swallow ?" }
};
var questions = quizz.Keys.ToList();
questions.Shuffle();
foreach (var question in questions)
{
Console.WriteLine(question);
if (Console.ReadLine() != quizz[question])
{
Console.WriteLine("You failed");
Console.ReadLine();
break;
}
else
{
Console.WriteLine("Nice !");
}
}
}
答案 1 :(得分:0)
为问题中的每个键输入答案。
foreach(var item in Questions) {
answers.Add(item.Key, "answer")
}
通过相同的随机问题索引将特定答案存储到另一个变量中
var askingQuestion = Questions.ElementAt(randomIndex);
var answerOfAskingQuestion = answers.ElementAt(randomIndex);
显示问题以从控制台读取答案
Console.WriteLine(answerOfAskingQuestion.value);
string input = Console.ReadLine();
现在将输入的内容与answerOfAskingQuestion的值进行比较
if (input.ToLower().Equals(answerOfAskingQuestion.Value.ToLower()) {
// given answer is correct
// display "your answer is correct"
Console.WriteLine("Your answer is correct");
} else {
// answer is wrong
// display "incorrect"
Console.WriteLine("Your answer is wrong");
}
答案 2 :(得分:0)
您应该创建一个“问题”类,其中包含问题文本,答案列表和正确答案。因此,您的Questions词典应为:
NULL