c# - C# 监听键并输出结果
问题描述
我有以下代码根据我按下的键输出 Meow 或 Awo。
它正在工作,但由于某种原因,在 do/while 的第一次迭代之后,我需要在 c 和 d 上按两次以使其输出任何内容。关于我如何以不同的方式做到这一点的任何想法?
using System;
namespace Program
{
interface Animal
{
void animalSound();
}
class Dog : Animal
{
public void animalSound()
{
Console.WriteLine(" Awo Awo!");
}
}
class Cat : Animal
{
public void animalSound()
{
Console.WriteLine(" Meow");
}
}
class Program
{
static void Main(string[] a)
{
Dog myDog = new Dog();
Cat myCat = new Cat();
Console.WriteLine("--------Press C to call the Cat--------");
Console.WriteLine("--------Press D to call the Dog--------");
Console.WriteLine("Press double ESC to close the program");
do
{
Console.WriteLine("Starting the do loop 1");
ConsoleKeyInfo KeyInfo = Console.ReadKey(true);
while (!Console.KeyAvailable)
{
Console.WriteLine("Starting the while loop 2");
if (KeyInfo.Key == ConsoleKey.C)
{
myCat.animalSound();
} else if(KeyInfo.Key == ConsoleKey.D) {
myDog.animalSound();
}
Console.WriteLine("Breaking the while loop 3");
break;
}
Console.WriteLine("Continue the do loop 4");
continue;
} while (Console.ReadKey(true).Key != ConsoleKey.Escape);
}
}
}
解决方案
想要第二个条目
Console.ReadKey(true).Key
循环条件中的用户
尝试这个:
Dog myDog = new Dog();
Cat myCat = new Cat();
Console.WriteLine("--------Press C to call the Cat--------");
Console.WriteLine("--------Press D to call the Dog--------");
Console.WriteLine("Press double ESC to close the program");
ConsoleKeyInfo KeyInfo;
int counter = 1;
do
{
KeyInfo = Console.ReadKey(true);
Console.WriteLine("Starting the while loop " + counter);
counter++;
if (KeyInfo.Key == ConsoleKey.C)
{
myCat.animalSound();
}
else if (KeyInfo.Key == ConsoleKey.D)
{
myDog.animalSound();
}
} while (KeyInfo.Key != ConsoleKey.Escape);
推荐阅读
- php - 我可以在 apatch 中的 php 文件中播放位于硬盘中的文件路径中的视频吗?
- angular - 如何修补嵌套表单数组?
- rust - 为什么 max_by_key 与 i32.log10() 导致“尝试添加溢出”
- python - 将华氏温度转换为摄氏度,反之亦然 python
- python - 如何装饰 Python 进程以捕获 HTTP 请求和响应?
- java - Java maven 无法在 Heroku 上启动应用程序。错误 H10(应用程序崩溃)
- express - 'return res.json' 没有按预期停止我的请求?
- java - Builder 无法转换为 HttpRequest
- html - 如何删除边框和内部内容之间的空间?
- visual-studio-code - VSCode 无法通过 workbench.colorCustomizations 或 editor.tokenColorCustomizations 自定义颜色主题