【问题标题】:Why does the `Console.Read()` keep jumping to another spot?为什么 `Console.Read()` 总是跳到另一个位置?
【发布时间】:2013-04-16 17:13:19
【问题描述】:

我有一个方法用来询问一个人想在Console 游戏中走哪条路。

上述方法:

私有静态 void dirChoose()

{
    Console.SetCursorPosition(0, 7);
    Console.WriteLine("A mysterious voice says \"Which way will you go?\"");
    Console.WriteLine("Type");
    if (curLeft == false) { Console.WriteLine("(L)eft    "); }
    if (curUp == false) { Console.WriteLine("(U)p        "); }
    if (curRight == false) { Console.WriteLine("(R)ight  "); }
    if (curDown == false) { Console.WriteLine("(D)own    "); }

    Console.SetCursorPosition(49, 7);

    userDirInput = Convert.ToChar(Console.Read());
    Console.SetCursorPosition(0, 13);
    Console.Write("read as " + userDirInput);

         if (userDirInput == 'u' || userDirInput == 'U') { reDir = 1; userDirInput = 'y'; }//up
    else if (userDirInput == 'd' || userDirInput == 'D') { reDir = 3; userDirInput = 'y'; }//down
    else if (userDirInput == 'l' || userDirInput == 'L') { reDir = 0; userDirInput = 'y'; }//left
    else if (userDirInput == 'r' || userDirInput == 'R') { reDir = 2; userDirInput = 'y'; }//right
    else//anything besides
    {
        Console.SetCursorPosition(0, 14);
        Console.WriteLine("You entered an incorrect direction. Please try again.");
        Console.SetCursorPosition(rWALL_STOP - 1, 3);

        doneBool = false;
        t.Elapsed += right;
        t.Start();

    }
}//dirChoose()

在回答“你会走哪条路?”的问题时应该读取输入的第一个字符。因此,如果您输入整个单词“left”或“right”,那么它会显示为“l”和“r”。然后它应该改变一个数字并让它做它应该做的事情。出于某种奇怪的原因,它在读取第一个后跳转到第二个,因此它将适当的方法添加到计时器并继续前进。

注意:

static Timer t = new Timer(16);
public static char userDirInput { get; set; }

public static bool curLeft { get; set; }
public static bool curUp { get; set; }
public static bool curRight { get; set; }
public static bool curDown { get; set; }
public static bool doneBool{ get; set; }

所以我的问题是“为什么光标会跳到第一个字符之后的第二个字符?我该如何解决?”

【问题讨论】:

    标签: c# if-statement timer console character


    【解决方案1】:

    您可以按如下方式读取密钥。将 false 值传递给 ReadKey() 将在屏幕上回显输入的值。

    ConsoleKeyInfo cki = Console.ReadKey(false);
    userDirInput = cki.KeyChar;
    

    而不是

    userDirInput = Convert.ToChar(Console.Read());
    

    【讨论】:

    • +1。但是...... ReadKey 的参数是倒退的。正如文档所说,“true 不显示按下的键”。我想你想要Console.ReadKey(true)
    • @JimMischel:感谢您指出错误。非常感激。 +1
    • 一分钟前刚试过这样做。效果不太好,因为每次我按下键时它都会读取它(我明白这就是它应该做的)但我需要它来读取第一个字母或读取整个字符串,我想我不会有很多问题。
    【解决方案2】:

    我不确定我是否理解您的问题,但您似乎误解了 Console.Read() 的行为。当您调用 Console.Read() 时,您将获得缓冲区中的下一个字符。如果用户键入“left”然后按回车,您将调用控制台读取以获取“l”,然后缓冲区中将剩下 5 个字符。下一个调用将返回 'e',然后是 'f',然后是 't',然后是 '\r',然后是 '\n'。

    因此,如果用户输入“left\r\n”,那么在您第二次调用 dirChoose() 时,它的行为将与无法识别的输入一样。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-05-28
      • 2019-02-28
      • 2021-11-04
      • 2022-01-22
      • 2015-01-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多