【发布时间】:2015-04-05 21:17:00
【问题描述】:
创建一个 C# 程序以提示用户从问题的答案选项列表中选择正确答案,如果答案错误,则尝试使用 do while 循环再次提示相同的问题,但它无法正常工作应该是。
class Program
{
static void Main(string[] args)
{
char UserChoice = ' ';
do
{
Console.WriteLine("What is the command keyword to exit a loop in C#?");
Console.WriteLine("a.quit");
Console.WriteLine("b.continue");
Console.WriteLine("c.break");
Console.WriteLine("d.exit");
UserChoice = ' ';
Console.WriteLine("Please enter a b c or d");
UserChoice = (char)Console.Read();
switch (UserChoice)
{
case 'a': Console.WriteLine("wrong ans"); break;
case 'b': Console.WriteLine("wrong ans"); break;
case 'd': Console.WriteLine("wrong ans"); break;
case 'c': Console.WriteLine("right"); break;
default: Console.WriteLine("Bad choice {0}", UserChoice); break;
}
} while (UserChoice == 'a' || UserChoice == 'b' || UserChoice == 'd');
}
}
但是如果我在这个程序中使用 int 而不是 char 并将 a、b、c 和 d 替换为 1、2、3 和 4,那么这个程序可以正常工作。请有人可以解释一下使用char时这段代码有什么问题。
【问题讨论】:
-
当你使用 char 时会发生什么?你得到错误?如果是这样,错误是什么?
-
@adv12 他的代码在这一点上似乎是正确的。 a,b,c 和 d 不是命令,它们是对命令含义的猜测。阅读所提问题的文字。
-
@Servy,是的,那是我略读的。谢谢。
-
因此,当我使用 char 运行程序时 -- 选择错误的答案,它会再次提示我同样的问题并选择错误的选择答案,这本身就是默认答案。这就是程序出错的地方。