import java.io.*;
public class TestN2 
{
public static void main(String args[]) throws IOException
{ double n,x;
try
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
n=Integer.parseInt(br.readLine());

        int s=1;
for( double i=1;i<=n;i++ )
{
   s*=i;
} System.out.println("n!="+s);
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("命令行没有输入参数或参数不足");
}
catch(NumberFormatException e)
{
System.out.println("输入的参数不是数字");
}
}
}计算n!并捕获可能出现的异常
我主要是不知道应该怎么自定义异常,捕捉n为负数,以及n不为整数的异常。
如果还有其他异常,也请指点一二~~~

解决方案 »

  1.   

    //自定义异常类
    public class ZDException extends Exception{
        public ZDExceptino(String s){
    }
    public ZDException(){
        super("");
    }
    }
    、、、、、、、、、、、、、、
      for( double i=1;i<=n;i++ )
                    {
                       s*=i;
                //添加
               if(s<0)
                   throw new ZDException("结果为复数异常");
      

  2.   

    同意楼上的解法,像这种问题,估计不用自定义异常,自定义异常用的不是很多,
    自定义异常有两种方法,一种是继承Exception类还有一种就是实现Throwsable接口...
      

  3.   

    把得到的double型变量转换为String变量:
    String str=""+n;
    if(str.contains(".")){
       System.out.println("It is not a Integer!!!");
    }
      

  4.   


    import java.io.*;
    class MyException1 extends Exception 
    {
    int devisor;
    public MyException(String s,double devisor)      //需要返回值
    {
    super(s);
    this.devisor=devisor;
    }
    public int getDevisor()
    {return devisor;}
    }public class TestN 
    {
    public static void main(String args[]) throws  IOException
    { double n,x;
    BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
    try
    {
    n=Integer.parseInt(br.readLine());
    }
    catch(ArrayIndexOutOfBoundsException e)
    {
    System.out.println("命令行没有输入参数或参数不足");
    }
    catch(NumberFormatException e)
    {
    System.out.println("输入的参数不是数字");
    }
    //x=Math.round(n);

    double s=1;
    for( double i=1;i<=n;i++ )
    {
       s*=i;
       try
       {
       if(s<0)
        throw new MyException1("n为负数",n);
        }
        catch(MyException1 e)
    {
    System.out.println(e.getMassage());
    System.out.println("n="+e.getDevisor());
    }
    } System.out.println("n!="+s);

    /*
    catch(MyException1 e)
    {
    System.out.println("输入的参数不是整数");
    }
    catch(MyException2 e)
    {
    System.out.println("输入的参数是负数");
    }*/
    }
    }求改正:错误提示为:第五行需要返回值(完全不理解)
      

  5.   


    public MyException(String s,double devisor) 这个不对,函数都是有返回值的,如果没有返回值的话,也要写出void类型,比如你这个就要写成public void MyException(String s,double devisor) 
      

  6.   

    用int保存最后的结果值,如果n大点就溢出了
      

  7.   


    throw new MyException()