首页 > 解决方案 > 为什么输入字符串格式不正确且未处理异常

问题描述

从用户获取数组输入时出现错误。

    static void Main(string[] args)
    {

        int[] arrSum = new int[] { };
        Console.WriteLine("Enter the array Size:\t");
        int n = Convert.ToInt32(Console.ReadLine());            
        Console.WriteLine("Enter the array elements of {0} as Array Size:\n",n);
        for (int i = 0; i < n; i++)
        {
           arrSum[i] = int.TryParse(Console.ReadLine(), out arrSum[]);
        }

        Console.WriteLine("Enter the number whose sum you want to find:\n");
        int j = Convert.ToInt32(Console.ReadLine());
        ArraySum(arrSum,n,j);

    }

    public static int ArraySum(int[] arr, int key, int n)
    {                                
        for (int i = 0; i < arr.Length; i++)
        {              
            int first = arr[i];

            for (int k = i+1; k < arr.Length; k++)
            {
                int second = arr[k];
                while (first + second == key)
                {
                    Console.WriteLine("The numbers whose sum is {0}" + key + "are:\n" + first + second);
                }

                if (first + second != key)
                {
                    return -1;                                               
                }                                     
                else
                {
                    return 1; 
                }                   
            }
        }
        return 0;
    }

要将数组大小和元素以及我们需要在用户提供的给定数组元素之间进行比较的数字作为输入,并返回其和等于给定数字的可能对。

标签: c#arrays

解决方案


我不确定我是否遇到了与您相同的问题,但我将您的代码修改如下。起初,我为整数创建了一个安全的控制台 readline 方法,如果输入了无效的整数,则不会引发异常:

 private static int GetIntFromInput()
    {
        while (true)
        {
            string value = Console.ReadLine();
            if (!int.TryParse(value, out int parsedInt))
            {
                Console.WriteLine("Invalid integer! Retry or Ctrl+C to abort program...");
                continue;
            }

            return parsedInt;
        }
    }

然后我修改了你的第一个方法如下:

static void Main(string[] args)
    {
        Console.WriteLine("Enter the array Size:\t");
        int n = GetIntFromInput();
        if (n <= 0)
        {
            Console.WriteLine("Array has to be at least of size 1...");
            return;
        }

        Console.WriteLine("Enter the array elements of {0} as Array Size:\n", n);

        var arrSum = new int[n];
        for (int i = 0; i < n; i++)
        {
            int newInt = GetIntFromInput();
            arrSum[i] = newInt;
        }

        Console.WriteLine("Enter the number whose sum you want to find:\n");
        int j = Convert.ToInt32(Console.ReadLine());
        ArraySum(arrSum, n, j);
    }

这样我的测试就成功了。请注意,我没有替换 j 的最后一个 Convert.ToInt32。

请注意,请始终尽可能验证用户输入,以免引发异常。如果任何时候你会检查任何不正确的东西,它肯定会在某个时候崩溃......

祝你有美好的一天!


推荐阅读