黑马程序员技术交流社区
标题:
实在想不懂,为什么只循环一次?
[打印本页]
作者:
油炸电视剧
时间:
2015-5-16 12:24
标题:
实在想不懂,为什么只循环一次?
题目是这样的:
1.现有Student类,属性有name, age, score(int类型).
要求 : 按照学生的分数排序, 分数大的童鞋在前面, 如果分数相同, 那么年龄小的在前面, 如果分数年龄都相同, 则按照姓名(英文的即可)的字典顺序排序.要求:不允许在描述类上写排序规则.
下面是给大家学生.
Student("Tom",24, 89)
Student("Robin",32, 99));
Student("Jerry",24, 99));
Student("Lili",23, 87));
Student("Jack",22, 87));
Student("LiLei",25, 95));
Student("Robin",32 ,99));
下面是我的代码:
package test;
import java.util.Comparator;
import java.util.Iterator;
import java.util.TreeSet;
public class Test1
{
public static void main(String[] args)
{
TreeSet set=new TreeSet(new MyComparator());
Student s1=new Student("Tom",24, 89);
Student s2=new Student("Robin",32, 99);
Student s3=new Student("Jerry",24, 99);
Student s4=new Student("Lili",23, 87);
Student s5=new Student("Jack",22, 87);
Student s6=new Student("LiLei",25, 95);
Student s7=new Student("Robin",32 ,99);
set.add(s1);
set.add(s2);
set.add(s3);
set.add(s4);
set.add(s5);
set.add(s6);
set.add(s7);
for(Iterator ite=set.iterator();ite.hasNext();)
{
Student s=(Student) ite.next();
System.out.println("成绩:"+s.getScore()+"年龄:"+s.getAge()+"姓名:"+s.getName());
}
}
}
class Student
{
String name;
int age;
int score;
public Student(String name, int age, int score)
{
this.age = age;
this.name = name;
this.score = score;
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public int getAge()
{
return age;
}
public void setAge(int age)
{
this.age = age;
}
public int getScore()
{
return score;
}
public void setScore(int score)
{
this.score = score;
}
}
class MyComparator implements Comparator
{
public int compare(Object o1, Object o2)
{
Student s1 = (Student) o1;
Student s2 = (Student) o2;
String n1 = s1.getName();
String n2 = s2.getName();
int l=Math.max(n1.length(), n2.length());
int a1 = s1.getAge();
int a2 = s2.getAge();
int sc1 = s1.getScore();
int sc2 = s2.getScore();
if (sc1 > sc2)
{
return -1;
}
else if (sc1 == sc2)
{
if (a1 > a2)
{
return 1;
}
else if (a1 == a2)
{
for (int i = 0; i < l-1; i++)
{
if (n1.charAt(i) > n2.charAt(i))
{
return 1;
}
if (n1.charAt(i) == n2.charAt(i))
{
return 0;
}
return -1;
}
}
return -1;
}
return 1;
}
}
复制代码
就是判断姓名的时候那里只会循环一次,而且只会输出6个结果。这是为什么?求大神指点以及改进!
作者:
xingfeichen
时间:
2015-5-16 19:16
额 。。一句注释都没有,老毕说了,这不是好习惯
作者:
我干阿衰
时间:
2015-5-17 00:14
本帖最后由 我干阿衰 于 2015-5-17 00:17 编辑
你这代码,我也是醉了,太乱了!!!而且除了迭代外好像也没有别的循环了吧?哪里还有名字的循环?你这写的真是太复杂了
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2