菜鸟关于return的问题....

wwnxs 2008-04-26 11:06:50
public class Fab {

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println(fab(8));

}

public static long fab(int index){
if(index<1){
System.out.println("error!");
return -1;
}

if(index == 1||index == 2){
return 1;
}

long f = 0, f1 = 1l, f2 = 1l;
for(int i = 1; i<=index-2; i++){
f = f1 + f2;
f1 = f2;
f2 = f;

}
return f;
}
}





上面这个程序,如果把return f;放在for循环里,即:

public class Fab {

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println(fab(8));

}

public static long fab(int index){
if(index<1){
System.out.println("error!");
return -1;
}

if(index == 1||index == 2){
return 1;
}

long f = 0, f1 = 1l, f2 = 1l;
for(int i = 1; i<=index-2; i++){
f = f1 + f2;
f1 = f2;
f2 = f;
return f;
}

}
}




把return放在for循环里会报错,提示“This method must return a type of long”,为什么会提示返回值f和声明的long类型不符呢?
...全文
145 10 打赏 收藏 转发到动态 举报
写回复
用AI写文章
10 条回复
切换为时间正序
请发表友善的回复…
发表回复
wwnxs 2008-04-27
  • 打赏
  • 举报
回复
[Quote=引用 6 楼 huanlingpiaohun 的回复:]
3楼已经给出正确答案了...

顺便说一下
编译器报的错是"有没有"返回值的问题,不是"什么类型"返回值的问题...
[/Quote]


哦。。。晕。。。英语啊英语。。。
yiyi_wx 2008-04-27
  • 打赏
  • 举报
回复
你把return放在for里面 相当于缺少了返回值啊
两个if判断中分别有各自的return值 但是if后的模块却没有
如果lz想把return放进for循环 在循环外要再加一个return 0;(或其他 起标识作用)
lz试试~
huanlingpiaohun 2008-04-27
  • 打赏
  • 举报
回复
哦,对不起,是2楼
huanlingpiaohun 2008-04-27
  • 打赏
  • 举报
回复
3楼已经给出正确答案了...

顺便说一下
编译器报的错是"有没有"返回值的问题,不是"什么类型"返回值的问题...
wwnxs 2008-04-27
  • 打赏
  • 举报
回复
[Quote=引用 4 楼 hujing101 的回复:]
当执行f = f1 + f2的时候f已经是int型的了而你定义的f是long型 有冲突所以有错
[/Quote]

怎么会呢?在for循环前已经定义了f1,f2的值都是1L。怎么还会是int呢。
hujing101 2008-04-27
  • 打赏
  • 举报
回复
当执行f = f1 + f2的时候f已经是int型的了而你定义的f是long型 有冲突所以有错
aipb2008 2008-04-27
  • 打赏
  • 举报
回复
记住一点
要保证函数的每一条path都有返回。

所以如果程序逻辑能到达for循环外,那么没有返回就报错了。
而3楼说的return放for里没意义是不对的,这要看程序逻辑。
Sany_J2SE 2008-04-26
  • 打赏
  • 举报
回复
这里不是type的问题吧
return f放在for{}里面的话for不是失去意义了么?
我是风 2008-04-26
  • 打赏
  • 举报
回复
把return放在for循环里, 当程序运行到循环临界,但循环条件不满足时,程序直接运行循环体后的语句。LZ的程序在循环体后结束了,但没有返回语句,所以报错。
wwnxs 2008-04-26
  • 打赏
  • 举报
回复
晕,忘记排版了....没有修改权限,慢慢看一下吧 -_-#

62,614

社区成员

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

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