首页 > 解决方案 > 在arrayc#中输入字符串时有没有办法抛出异常?

问题描述

我是这个迷人的编程世界的新手。我已经完成了这个数组,但是当我输入一个非整数时它崩溃了。我尝试了很多方法,例如 int.Parse(console.readLine))、tryparse(text, out int) 和 ConvertTo32,但是它继续说“输入字符串的格式不正确”。谢谢

使用系统;

命名空间 BubbleSort { 类程序 {

    public static void HelpME(int[] a, int t)
    {
        for (int j = 0; j <= a.Length - 2; j++)
        {
            for (int i = 0; i <= a.Length - 2; i++)
            {
                if (a[i] > a[i + 1])
                {
                    t = a[i + 1];
                    a[i + 1] = a[i];
                    a[i] = t;
                }
            }
        }
    }

    static void Main(string[] args)
    {
        int[] num = { 1, 2, 3, 4, 5 };
        int[] a = new int[5];


        for (int x = 0; x < 5; x++)
        {
            Console.WriteLine($"Input enter {num[0 + x]} of five");
            a[0 + x] = Convert.ToInt32(Console.ReadLine());
                                    
        }

        Console.WriteLine("The Array is : ");

        for (int i = 0; i < a.Length; i++)
        {
            Console.WriteLine(a[i]);
        }


        {

            HelpME(num, 5);

        }

        Console.WriteLine("The Sorted Array :");

        foreach (int aray in a)
        {
            Console.Write(aray + " ");
        }
        Console.ReadLine();
    }
}

}

标签: c#arraysexceptionthrow

解决方案


您应该使用 int.TryParse 方法验证用户未输入。如果输入的字符串可以转换为 int,那么只有它应该被插入到数组中,否则程序应该忽略该值。

static void Main(string[] args)
{
    int[] num = { 1, 2, 3, 4, 5 };
    int[] a = new int[5];


    for (int x = 0; x < 5; x++)
    {
        Console.WriteLine($"Input enter {num[0 + x]} of five");
        int temp = 0;
        
        string input = Console.ReadLine();
        
        if(int.TryParse(input, out temp))
        {
          a[0 + x] = Convert.ToInt32(input);
        }
                                
    }

    Console.WriteLine("The Array is : ");

    for (int i = 0; i < a.Length; i++)
    {
        Console.WriteLine(a[i]);
    }


    {

        HelpME(num, 5);

    }

    Console.WriteLine("The Sorted Array :");

    foreach (int aray in a)
    {
        Console.Write(aray + " ");
    }
    Console.ReadLine();
}

推荐阅读