c#输入一个字符,将字符转化为数字返回,带处理异常代码

输入一个字符,将字符转化为数字返回

static int input()//输入一个字符,将字符转化为数字返回
        {
            while (true)
            {
                try
                {
                    int choose = Convert.ToInt32(Console.ReadLine());
                    return choose;
                }
                catch (ArgumentNullException)
                {
                    Console.WriteLine("输入错误,请重新输入!");
                }
                catch (FormatException)
                {
                    Console.WriteLine("输入错误,请重新输入!");
                }
                catch (OverflowException)
                {
                    Console.WriteLine("输入错误,请重新输入!");
                }
            }
        }

输入一个字符,将字符转化为以’/'分割数字数组返回,如输入“1/22”,返回{1,22}

        static int[] input2()//,输入一个字符,将字符转化为以'/'分割数字数组返回,如输入“1/22”,返回{1,22}
        {
            while (true)
            {
                try
                {
                    string str = Console.ReadLine();
                    int a = 0;
                    for (int i = 0; i < str.Length; i++)
                    {
                        if (str[i] == '/')
                        {
                            a++;
                        }
                    }

                    if (a == 0)
                    {
                        string[] str2 = { str, "1" };
                        int b1 = Convert.ToInt32(str2[0]);
                        int b2 = Convert.ToInt32(str2[1]);
                        int[] str3 = { b1, b2 };
                        return str3;
                    }
                    else if (a == 1)
                    {
                        string[] str1 = str.Split('/');
                        int a1 = Convert.ToInt32(str1[0]);
                        int a2 = Convert.ToInt32(str1[1]);
                        int[] arr = { a1, a2 };
                        return arr;
                    }
                    else
                    {
                        Console.WriteLine("输入错误,请重新输入!");
                    }
                }
                catch (ArgumentNullException)
                {
                    Console.WriteLine("输入错误,请重新输入!");
                }
                catch (FormatException)
                {
                    Console.WriteLine("输入错误,请重新输入!");
                }
                catch (OverflowException)
                {
                    Console.WriteLine("输入错误,请重新输入!");
                }
            }
        }


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

烧仙草奶茶

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值