簡體   English   中英

按 Enter 時阻止程序崩潰

[英]Stop program from crashing when pressing Enter

所以,今天我決定從零開始學習 C#。 我已經設法制作了一個小數學問題程序。 問題是,只要用戶在沒有輸入值(或任何非數字)的情況下按下回車,程序就會崩潰。 我讀過一些關於 TryParse 的文章,但我就是不明白。 這是我的代碼(部分):

    {
        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;
        }

提前致謝!

您好,歡迎來到 StackOverflow:我有幾個建議:

  1. 避免使用goto
  2. 每當用戶為您提供價值時,將所有Convert.X替換為X.TryParse ,因為您不知道它可能是什么
Random numberGenerator = new Random();
int num01 = numberGenerator.Next(1, 20);
int num02 = numberGenerator.Next(1, 20);

Console.WriteLine("Welcome, user.");
Console.ReadKey();

// Always use a loop instead of goto statements!
while (true)
{
    Console.WriteLine("¿What's " + num01 + "x" + num02 + "?");

    // Old line: int res1 = Convert.ToInt32(Console.ReadLine());
    // Problem: this assumes that Console.ReadLine() returns a valid number, e.g. "3"
    //          but as you said, the user can trick you and put something else

    if (!int.TryParse(Console.ReadLine(), out int res1))
        continue; // This will rerun the loop from the top, so the user will need to re-write a response


    if (res1 == num01*num02)
    {
        Console.WriteLine("Your answer is correct");
        Console.ReadKey();
    }
    else
    {
        break; // stop the outer loop on top
    }
}

像這樣使用 int.TryParse ...

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

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

https://docs.microsoft.com/en-us/dotnet/api/system.int32.tryparse?view=netcore-3.1

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM