java初学者,有个小问题请教!
我想实现一个递归方法,求n的阶层。
我的代码是这样的:
public class S{
long F(int n) {
if (n == 1)
return 1;
else
return n*F(n-1);
}
public static void main(String args[]){
int n = System.in.read();
S i = new S();
System.out.println(i.F(n));
}
为什么这样写的时候编译通不过会报以下错误:
unreported exception java.io.IOException; must be caught or declared to be thrown
于是我就改成:
public class S{
long F(int n) {
if (n == 1)
return 1;
else
return n*F(n-1);
}
public static void main(String args[]){
try{
int n = System.in.read();
S i = new S();
System.out.println(i.F(n));
}catch(Exception e){System.out.println("error");}
}
}
但是运行时输入2得到的结果却是-3258495067890909184这是为什么??
而我不用int n = System.in.read();这句代码。
直接写System.out.println(i.F(2));的时候,结果却是正确的!
这是为什么啊?请指教!!