/*
编写一个计算阶乘的程序,当输入的数据是带小数时,引发异常。
* 提示:定义一个自定义异常类。
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
namespace ConsoleApplication2
{
class outofBoundException : ApplicationException
{
public outofBoundException(string msg)
: base(msg)
{ }
}
class Program
{
static void Main(string[] args)
{
try
{
Console.Write("请输入:");
string x = Console.ReadLine();
if (isxiaoshu(x))
{
//抛出异常,调用自定义异常类的有参构造函数
throw new outofBoundException("不允许为小数!");
}
int a = int.Parse(x);
int s=1;
for (int i = 1; i <= a; i++)
s = s * i;
Console.WriteLine("{0}!为:{1}",a,s);
}
catch (outofBoundException e)
{
Console.WriteLine(e.Message);
}
finally
{
Console.WriteLine("按任意键退出》》");
Console.ReadKey();
}
}
public static Boolean isxiaoshu(string val) //练习一下正则表达式
{
Regex rex = new Regex(@"\d*[.]\d*");
Match m = rex.Match(val);
return m.Success;
}
}
}
运行结果: