【问题标题】:How to catch exception inside my do while loop如何在我的 do while 循环中捕获异常
【发布时间】:2019-01-18 08:47:00
【问题描述】:

我的问题是,在捕获第一个异常后,变量number 已经有一个非零值,所以当第二个异常被抛出时。它只是跳出了我的 do-while 循环。我希望能够根据用户输入捕获两个或更多异常,而不会跳出循环。

有什么想法吗?我是编码新手,所以希望你能保持简单:)

int number = 0;
int svar = 2; // set by the user; for example 2

do
{
    try
    { 
       for (int i = 0; i < svar; i++)
       {
           Console.Write("\nWrite the number you would like to add to your list: ");
           nummer = int.Parse(Console.ReadLine());
       }

    }
    catch
    {
        Console.WriteLine("\n-- ERROR --");
        Console.WriteLine("You typed a letter instead of a number, try again!");
    }

    myList.Add(number);

} while (number == 0);

【问题讨论】:

  • 第二个异常发生在哪里?
  • nummer number。真正尝试提供一个真实的、可编译的代码示例
  • 尝试使用int.TryParse(string, out int value) 和 if 语句来查看它是否成功解析而无需捕获错误。 Here's 一个很好的教程/展示差异
  • 我建议重写你的逻辑并使用 TryParse 而不是手动处理异常
  • 现在有意义吗?

标签: c# for-loop try-catch do-while


【解决方案1】:

让我们保持代码简单 - 让我们提取方法 InputInteger;另一个建议是使用TryParse 而不是异常捕获

   private static int InputInteger(string title) {
     Console.WriteLine(); 

     // Keep on asking user
     while (true) {
       if (!string.IsNullOrEmpty(title)) 
         Console.Write(title);

       // if correct integer value provided, return it
       if (int.TryParse(Console.ReadLine(), out var result)) 
         return result;

       // in case of syntax error print the message
       Console.WriteLine("-- ERROR --");
       Console.WriteLine("Please, type integer number, try again!");
     }
   }  

然后你可以在需要用户输入整数值时使用它:

   int svar = InputInteger("How many items would you like to have in the list?");

   ...

   // get svar integer items 
   for (int i = 0; i < svar; ++i)
     myList.Add(InputInteger("Write the number you would like to add to your list: ")); 

【讨论】:

  • 太好了,您从问题中解决了一个方法,然后在添加到列表时使用它。
【解决方案2】:

您可以使用int.TryParse,请参见下面的示例

 for (int i = 0; i < svar; i++)
 {
     Console.Write("\nWrite the number you would like to add to your list: ");
     while (!int.TryParse(Console.ReadLine(), out number))
     {
         Console.WriteLine("\n-- ERROR --");
         Console.WriteLine("You typed a letter instead of a number, try again!");
     }

     myList.Add(number);
 }

【讨论】:

  • 不错!谢谢 opewix 完成了这项工作,但我并没有真正遵循代码......解释? :)
  • @Japoc int.TryParse 当字符串为有效数字时返回true,否则返回false。在while 循环中,我们等待用户输入并尝试将其解析为数字。如果我们没有得到数字,我们会向用户打印一条消息并一次又一次地等待用户输入
【解决方案3】:

你需要像这样在里面使用 try 块

  int number = 0;
int svar = set by the user for exempel 2

do
{

       for (int i = 0; i < svar; i++)
       {
 try
  {
       Console.Write("\nWrite the number you would like to add to your list: ");
       nummer = int.Parse(Console.ReadLine());
   }

   catch
   {
   Console.WriteLine("\n-- ERROR --");
   Console.WriteLine("You typed a letter instead of a number, try again!");
   }

   myList.Add(number);

   }

} while (number == 0);

【讨论】:

  • 我一开始也是这样,但它产生了同样的问题
  • 然后你可以在catch中重新分配编号为0。
  • 你的意思是我会输入“number = 0;”在错误消息之后?
  • 遗憾的是它没有用..我写了“number = 0”和“i--;”在错误消息之后。循环有效,当用户输入最少 2 个数字时,它会中断循环,但之后当我尝试打印列表时,它只显示其中一个数字..
【解决方案4】:

感谢您是编码新手。欢迎您,希望您喜欢它。

我对代码进行了一些重构,使其更简单且无错误:

using System;
using System.Collections.Generic;
using System.Linq;

namespace ConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            ProcessNumbers();
        }

        private static void ProcessNumbers()
        {
            var myList = new List<int>();
            string sinput = String.Empty;
            var number = 0;
            do
            {
                try
                {
                    Console.Write("Write the number you would like to add to your list (type stop when you are done): ");
                    var input = Console.ReadLine();

                    if(input != "stop")
                    {
                        number = int.Parse(input);
                        myList.Add(number);
                    }
                    else
                    {
                        sinput = input;
                    }
                }
                catch
                {
                    Console.WriteLine("ERROR: You typed a letter instead of a number, try again!");
                }

            } while (sinput != "stop");

            var sum = myList.Sum();
            Console.WriteLine("The sum of all your numbers is: " + sum);
            Console.Write("Press any key to exist...");
            Console.ReadKey();
        }
    }
}

基本上,它会不断要求用户继续输入数字,直到用户停止输入。最后,它将显示所有数字的总和。如果您对代码有任何疑问,请告诉我。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-02-23
    • 2015-07-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多