错误输入后C#重新输入值而不是重新启动程序

时间:2018-02-22 12:12:53

标签: c#

所以我试图用c#制作一个乘法表,我希望当用户在代码中输入错误时,它不应该从开始启动程序,而只是要求重新输入该值。当我运行此代码并输入错误的输入时。它会要求再次显示乘法表。但我希望如果我在“起始值”给出错误输入,那么它只会要求重新输入起始值而不是整个输入

public void Multi()
{
    Console.Write("\n\n");
    bool tryAgain = true;
    while (tryAgain)
    {
        try
        {

            Console.Write("Display the multiplication table:\n ");
            int t = Convert.ToInt16(Console.ReadLine());
            Console.WriteLine("\n");
            Console.WriteLine(" Start value ");

            Console.WriteLine("\n");
            Console.WriteLine(" End value \n");
            int end = Convert.ToInt32(Console.ReadLine());
            Console.WriteLine("\n");
            SwapNum(ref start, ref end);
            Console.Write("\n");
            Console.WriteLine("Display the table\n");
            int i = start;

            do
            {
                Console.WriteLine(t + " * " + i + " = " + t * i);
                //Console.WriteLine("{0} * {1} = {2}", t, i, t*i);
                i++;
            } while (i <= end);

        }

        catch (Exception ex)
        {
            Console.WriteLine("Please Enter the inter number ");
        }
    }
}
static void SwapNum(ref int x, ref int y)
{

    if (x >= y)
    {
        int temp = x;
        x = y;
        y = temp;
    }
}

1 个答案:

答案 0 :(得分:1)

Parse更改为TryParse;让为此

提取方法
  private static int ReadInt(string prompt) {
    while (true) {
      Console.WriteLine(prompt);

      int result;

      if (int.TryParse(Console.ReadLine(), out result))
        return result;

      Console.WriteLine("Sorry, it's not a correct integer value, please try again.");
    }
  }

  ...

  public void Multi() {
    Console.Write("Display the multiplication table:\n ");

    // Now we keep asking user until the correct value entered 
    int t = ReadInt("Start value");
    ...
  }