黑马程序员技术交流社区

标题: 程序编译报错是为什么呢?找不到解决办法请教大家帮忙了 [打印本页]

作者: 马晓平    时间: 2013-10-28 10:40
标题: 程序编译报错是为什么呢?找不到解决办法请教大家帮忙了
import java.util.*;
class Student_1 implements Comparable

{
        private String name;
        private int age;

Student_1(String name,int age)
{
        this.name=name;
        this.age=age;
}
public int compareTo(Object obj)
{
        if(!(obj instanceof Student_1))
                throw new RuntimeException("bushi xueshengduixiang");
        Student_1 s=(Student_1)obj;
       
        if(this.age>s.age)
                return 1;
        if(this.age==s.age)
        {
                return this.name.compareTo(s.name);
        }
        return -1;
}
public String getName()
{
        return name;
}
public int getAge()
{
        return age;
        }
}
class TreeSetDemo1
{
        public static void main(String[] args)
        {
                TreeSet ts=new TreeSet(new MyCompare());
               
                ts.add(new Student_1("lisi002",21));
                ts.add(new Student_1("lisi03",22));
                ts.add(new Student_1("lisi04",25));
                ts.add(new Student_1("lisi005",26));
                ts.add(new Student_1("lisi005",29));
                Iterator it=ts.iterator();
                while(it.hasNext())
                {
                        Student_1 stu=(Student_1)it.next();
                        System.out.println(stu.getName()+"...."+stu.getAge());
                }
        }

}
class MyCompare implements Comparator
{
        public int compare(Object o1,Object o2)
        {
                Student_1 s1=(Student_1)o1;
                Student_1 s2=(Student_1)o2;
                int num=s1.getName().compareTo(s2.getName());
                if(num==0)
                {
                        if(s1.getAge()>s2.getAge())
                                return 1;
                        if(s1.getAge()==s2.getAge());
                                return 0;
                                return -1;
                }
               
                return num;
        }
}

编译报异常错误
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
        Unreachable code
但是把循环中的return -1;注释掉就可以通过这是怎么回事呢?
if(num==0)
                {
                        if(s1.getAge()>s2.getAge())
                                return 1;
                        if(s1.getAge()==s2.getAge());
                                return 0;
                                return -1;
                }
作者: linjl_ll    时间: 2013-10-28 10:56
哥们,你的这条语句if(s1.getAge()==s2.getAge());右面多个了;
作者: 雨过丶天已晴    时间: 2013-10-28 11:00
if(s1.getAge()==s2.getAge());
                                return 0;
                                return -1;
if判断句后面多了一个";"号,这样你就有两个return,肯定报错
作者: 黄炳期    时间: 2013-10-28 11:58
如果问题已经解决,请及时修改主题至“提问结束”。
作者: To    时间: 2013-10-29 21:28
楼主你好,如果问题已解决请将帖子状态修改为提问结束,
如果未解决请继续追问,谢谢合作
修改方法请看解释帖:http://bbs.itheima.com/thread-89313-1-1.html




欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2