提问者:小点点

我如何做类似if(在if==“x”之前键入键)[closed]的操作


我是一个C#新手,想做一个简单的测试,因为我还没有做界面测试的想法,所以我试了一个非常简单的测试,像这样

Console.WriteLine("question");
Console.WriteLine("a" + " " + " " + " " + " " + "b" + " " + " " + " " + " " + "c");
Console.ReadLine();
 if (Console.ReadLine() == "a")
            {
                Console.WriteLine("comment");
            }
 else if (Console.ReadLine() == "b")
            {
                Console.WriteLine("comment");
            }
 else if (Console.ReadLine() == "c")
            {
                Console.WriteLine("comment");
            }

我知道这很可怕,但我看不到任何其他方法来做一个测验在我目前的水平,直到知道,我不明白为什么它让我键入答案a三次,然后我意识到阅读行做这是我可以做一些事情,以这种简单的方式,还是我需要加强我的编程技能?


共3个答案

匿名用户

使用Switch语句,在这种情况下更快更简洁,并将结果保存到一个变量中。

多个console.readline()将导致多个询问应答。

Console.WriteLine("question");
string userChoice = Console.ReadLine();
switch (userChoice)
{
    case "a":
        Console.WriteLine("Your choice was a");
        break;
    case "b":
        Console.WriteLine("Your choice was b");
        break;
    case "c":
        Console.WriteLine("Your choice was c");
        break;
}

你应该先阅读文档或者C#教程。

匿名用户

将结果保存在字符串变量中并引用它:

string choice = Console.ReadLine();
if (choice == "a")
{
    Console.WriteLine("comment");
}
else if (choice == "b")
{
    Console.WriteLine("comment");
}

匿名用户

您还可以使用“for”循环来显示答案列表:

List<string> answers = new List<string>();

answers.Add("answer 1");
answers.Add("answer 2");
answers.Add("answer 3");

Console.WriteLine("question");

for (int i = 0; i < answers.Count; i++)
    Console.WriteLine((char)('a' + i) + "." + answers[i]);

使用此代码,您将能够清除并填写每个问题的答案列表。