C# 按Enter键时停止程序崩溃

C# 按Enter键时停止程序崩溃,c#,C#,所以,今天我决定从头开始学习C。我已经设法做了一个小数学题程序。问题是,每当用户只按enter键而不输入值或任何不是数字的东西时,程序就会崩溃。我读过一些关于特里帕斯的书,但我就是搞不懂。 以下是我的代码部分: { Random numberGenerator = new Random(); int num01 = numberGenerator.Next(1, 20); int num02 = numberGenerator.Next(1

所以,今天我决定从头开始学习C。我已经设法做了一个小数学题程序。问题是,每当用户只按enter键而不输入值或任何不是数字的东西时,程序就会崩溃。我读过一些关于特里帕斯的书,但我就是搞不懂。 以下是我的代码部分:

    {
        Random numberGenerator = new Random();
        int num01 = numberGenerator.Next(1, 20);
        int num02 = numberGenerator.Next(1, 20);

        Console.WriteLine("Welcome, user.");
        Console.ReadKey();
        Fail2:
        Console.WriteLine("¿What's " + num01 + "x" + num02 + "?");
        int res1 = Convert.ToInt32(Console.ReadLine());
        if (res1 == num01*num02)
        {
            Console.WriteLine("Your answer is correct");
            Console.ReadKey();
        }
        else
        {
            goto Fail;
        }

提前谢谢

像这样使用int.TryParse

int res1 = 0;
if (!int.TryParse(Console.ReadLine(), out res1)) 
{
    //failed;

}
if (res1 == num01*num02)
...

您好,欢迎来到StackOverflow!我有几个建议:

避免使用goto 无论何时,只要用户向您提供值,就用X.TryParse替换所有Convert.X,因为您不知道它可能是什么 随机数发电机=新随机数; int num01=numberGenerator.Next1,20; int num02=numberGenerator.Next1,20; Console.WriteLineWelcome,用户。; Console.ReadKey; //始终使用循环而不是goto语句! 虽然是真的 { Console.WriteLine?什么是+num01+x+num02+?; //旧行:int res1=Convert.ToInt32Console.ReadLine; //问题:假设Console.ReadLine返回有效数字,例如3 //但正如你所说的,用户可以欺骗你,然后放置其他东西 如果!int.tryparseconole.ReadLine,out int res1 continue;//这将从顶部重新运行循环,因此用户需要重新写入响应 如果res1==num01*num02 { Console.writeline你的答案是正确的; Console.ReadKey; } 其他的 { break;//停止顶部的外部循环 } }
您可以使用int.TryParse而不是Convert.ToInt32。使用goto不是一个好方法,而loop则更值得一读:TryParse方法系列至少需要两个参数。第一个是包含wannabe编号的字符串,第二个是变量,如果解析成功,则应将解析结果存储在该变量中。如果一切顺利,TryParse将返回true,否则将返回false,并使用其类型的默认值设置第二个参数。如果无法解析第一个参数,则不会触发异常。此语法要求存在out关键字,以允许将结果存储在传递的参数中