java初学者,有个小问题请教!

FLW1980 2003-08-20 04:01:08
我想实现一个递归方法,求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));的时候,结果却是正确的!

这是为什么啊?请指教!!
...全文
40 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
FLW1980 2003-08-20
  • 打赏
  • 举报
回复
谢谢!
javahui 2003-08-20
  • 打赏
  • 举报
回复

输入2,其实是ASCII的值是0X32,十进制的50,所以n=50而不是1。

修改方法:
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 = Integer.valueOf(new java.io.DataInputStream(System.in).readLine()).intValue();
S i = new S();
System.out.println(i.F(n));
}catch(Exception e){System.out.println("error");}
}
}
javahui 2003-08-20
  • 打赏
  • 举报
回复
int n = System.in.read();
读入的是你输入的第一个字符的ASCII的值。
比如你输入1,其实是ASCII的值是0X31,十进制的49,所以n=49而不是1。

62,616

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧