C# 尝试创建一个菜单,如果用户输入了无效的内容,该菜单将不断重复
这里完全是初学者,昨天我第一次开始学习编程,所以请不要评判 我正在尝试制作一个程序,允许用户输入视频游戏的名称和分数,然后根据要求显示这些分数。我在做菜单。我注意到,如果用户在没有输入任何数字的情况下按enter键,程序会崩溃,我想避免这种情况,但我被卡住了。如果我按enter键,它不会崩溃。但是,如果我输入1或2,菜单会一直运行,如果我按enter键之后没有输入任何内容,那么它会崩溃吗?我迷路了C# 尝试创建一个菜单,如果用户输入了无效的内容,该菜单将不断重复,c#,menu,C#,Menu,这里完全是初学者,昨天我第一次开始学习编程,所以请不要评判 我正在尝试制作一个程序,允许用户输入视频游戏的名称和分数,然后根据要求显示这些分数。我在做菜单。我注意到,如果用户在没有输入任何数字的情况下按enter键,程序会崩溃,我想避免这种情况,但我被卡住了。如果我按enter键,它不会崩溃。但是,如果我输入1或2,菜单会一直运行,如果我按enter键之后没有输入任何内容,那么它会崩溃吗?我迷路了 namespace videogaems { class Program {
namespace videogaems
{
class Program
{
static void Main(string[] args)
{
menu();
}
static void menu()
{
int option = 0;
Console.WriteLine("Select what you want to do: ");
Console.WriteLine("1- add game");
Console.WriteLine("2- show game rating");
bool tryAgain = true;
while (tryAgain)
{
try
{
while (option != 1 || option != 2)
{
option = Convert.ToInt32(Console.ReadLine());
tryAgain = false;
}
}
catch (FormatException)
{
option = 0;
}
}
}
Convert.ToInt32(Console.ReadLine())
将在字符串无法转换为整数时引发异常。相反,您应该使用int.TryParse
,它接受一个字符串
和一个输出
参数,该参数设置为转换后的值(如果成功)。它返回一个bool
,指示它是否成功
例如,只要int.TryParse
失败,以下代码就会循环,成功后,userInput
将包含转换后的数字:
int userInput;
while (!int.TryParse(Console.ReadLine(), out userInput))
{
Console.WriteLine("Please enter a whole number");
}
但是,另一个选项是只使用
Console.ReadKey()
,它返回一个ConsoleKeyInfo
对象,该对象表示用户按下的键。然后我们可以只检查键字符的值(并忽略任何无效的键)
例如:
static void Menu()
{
bool exit = false;
while (!exit)
{
Console.Clear();
Console.WriteLine("Select what you want to do: ");
Console.WriteLine(" 1: Add a game");
Console.WriteLine(" 2: Show game rating");
Console.WriteLine(" 3: Exit");
ConsoleKeyInfo userInput = Console.ReadKey();
Console.WriteLine();
switch (userInput.KeyChar)
{
case '1':
// Code to add a game goes here (call AddGame() method, for example)
Console.Clear();
Console.WriteLine("Add a game was selected");
Console.WriteLine("Press any key to return to menu");
Console.ReadKey();
break;
case '2':
// Code to show a game rating goes here (call ShowRating(), for example)
Console.Clear();
Console.WriteLine("Show game rating was selected");
Console.WriteLine("Press any key to return to menu");
Console.ReadKey();
break;
case '3':
// Exit the menu
exit = true;
break;
}
}
}
option=Convert.ToInt32(Console.ReadLine())代码>是问题所在。如果不是数字,它就会崩溃。Dooption=int.TryParse(Console.ReadLine(),out int number)?编号:0代码>这将尝试并解析该值,如果成功,则编号
将被分配该值,然后分配给选项
,否则将分配0
。欢迎访问。您的代码似乎在option=Convert.ToInt32(Console.ReadLine())上抛出异常代码>尝试调试它并查看您看到的异常类型。您可以通过为异常分配一个变量,如catch(exception ex)
并查看ex
中的内容来实现这一点。谷歌搜索这个例外,你会发现你的答案while循环的逻辑条件是错误的。如果选项不是1也不是2,则应进入循环。所以应该是while(option!=1&&option!=2),在任何情况下都不应该使用异常来驱动代码。特别是当有可能避免的时候。Int32.TryParse是将用户输入转换为integer@Bizhan这会起作用,并使异常处理变得多余,谢谢