- Java code
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不为整数的异常。
如果还有其他异常,也请指点一二~~~
------解决方案--------------------
//自定义异常类
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("结果为复数异常");