求救:菜鸟新问题,代码不能运行?

asiazmm 2007-06-15 02:05:04
public class ifElse {
static int test(int testval, int target) {
int result = 0;
if(testval > target)
result = -1;
else if(testval < target)
result = 1;
else
return result;
}
public static void main(String [] args) {
System.out.println(test(5, 10));
System.out.println(test(5, 10));
System.out.println(test(5, 5));
}
}
...全文
185 10 打赏 收藏 转发到动态 举报
写回复
用AI写文章
10 条回复
切换为时间正序
请发表友善的回复…
发表回复
chen01lin 2007-06-15
  • 打赏
  • 举报
回复
public class ifElse {

static int test(int testval, int target) {
int result;
if(testval > target)
result=-1;
else if(testval < target)
result=1;
else
result=0;
return result;

}
public static void main(String [] args) {
System.out.println(test(5, 10));
System.out.println(test(5, 10));
System.out.println(test(5, 5));
}
}
asiazmm 2007-06-15
  • 打赏
  • 举报
回复
呵呵 再次感谢 bao110908(Baobao) ( ) 信誉:100 Blog 加为好友
多么好的人啊 咯咯
  • 打赏
  • 举报
回复
回复人:asiazmm() ( 一级(初级)) 信誉:100 2007-06-15 14:28:48 得分:0

public class ifElse {
  static int test(int testval, int target) {
    if(testval > target)
      return -1;
    else if(testval < target)
      return +1;
    else
      return 0;
  }
}
在这个里面为什么没有用加的那几个{}可以运行呢?

==============================================

因为这里的if和else语句里只有一句语句,所以可以不用加 { } 呀
如果其中有超过一条语句的话,就必须加上 { } 否则可能得到不对的结果。

建议:无论里面有多少语句都加上 { } 这样有利于代码的可读性。

* * * *

另外顺便说一句,public class ifElse 中的“ifElse”改为“IfElse”(类名使用大写字母开头),虽然用小写没有错,但这样比较符合规范。
asiazmm 2007-06-15
  • 打赏
  • 举报
回复
明白了谢谢大虾们了
xiaoniaoxiangfei 2007-06-15
  • 打赏
  • 举报
回复
这个东西加上{}是没有原因的,要是有就是SUN是这么规定的。这是游戏规则。
asiazmm 2007-06-15
  • 打赏
  • 举报
回复
public class ifElse {
static int test(int testval, int target) {

if(testval > target)
return -1;
else if(testval < target)
return +1;
else
return 0;
}
public static void main(String [] args) {
System.out.println(test(10, 5));
System.out.println(test(5, 10));
System.out.println(test(5, 5));
}
}
在这个里面为什么没有用加的那几个{}可以运行呢?
bend01 2007-06-15
  • 打赏
  • 举报
回复
既然你指定要返回值,就要返回个值
asiazmm 2007-06-15
  • 打赏
  • 举报
回复
再请教下 能说说这样加{}的原因吗? 谢谢
  • 打赏
  • 举报
回复
static int test(int testval, int target) {
  if (testval > target)
    return -1;
  else if (testval < target)
    return 1;
  else
    return 0;
}

在 test 中 result 好像没有什么必要的,如果真的要的话把你原来的 test() 中 return result; 前的那个else擦掉就可以了。
guichenguang 2007-06-15
  • 打赏
  • 举报
回复
public class Test01 {
static int test(int testval, int target) {
int result = 0;
if(testval > target){
result = -1;
}else if(testval < target){
result = 1;
}
return result;

}
public static void main(String [] args) {
System.out.println(test(5, 10));
System.out.println(test(5, 10));
System.out.println(test(5, 5));
}
}

62,615

社区成员

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

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