【问题标题】:Difference between the char and int in C#C#中char和int的区别
【发布时间】: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 运行程序时 -- 选择错误的答案,它会再次提示我同样的问题并选择错误的选择答案,这本身就是默认答案。这就是程序出错的地方。

标签: c# char int


【解决方案1】:

如果你想阅读单个字符,你应该使用Console.ReadKey

Console.Read 等待来自控制台的输入,这意味着在大多数 shell 中读取整行,然后将输入的第一个字符的 ASCII 值作为int 提供给您。

如果你只使用ReadKey,你可以得到一个实际的char,代表按下的下一个字符,而不必担心如何将你得到的转换成char

【讨论】:

  • 它不允许我使用 char UserChoice = Console.Readkey();正如错误所说——> 不能将 System.Consolekeyinfo 类型隐式转换为 char。
  • 我用过 ConsolekeyInfo UserChoice = Console.ReadKey();然后使用 UserChoice.keyChar 在代码中任何需要的地方使用。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-09-10
  • 1970-01-01
  • 1970-01-01
  • 2016-05-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多