我在这里是新来的,并决定开始回答较简单的问题来帮助练习我的编码技巧......这是我的解决方案,基于杰罗姆的建议。
虽然有点冗长,但我认为它足够灵活,可以满足任何变化,例如需要更多人员或不同的排序标准。
首先是主程序。它包含一个main和一个函数,用于排序并打印出前两个。
package answer.keyte;
import java.util.ArrayList;
import java.util.Collections;
/**
* @author aaron
*
* Sort the names of people by the values they are given. Show the top
* two. Show "no more people" if there aren't at least two with scores
* above 0.</br>
* Response to:</br>
* http://stackoverflow.com/questions/9505815/displaying-top
* -two-results-in-java
*/
public class SO_9505815 {
public static void main(String[] args) {
// get data from somewhere
ArrayList<Person> people = new ArrayList<Person>();
Person tom = new Person("Tom", 20);
Person john = new Person("John", 10);
Person paul = new Person("Paul", 0);
//show top two for only one person
people.add(john);
showTopTwo(people);
System.out.println();
//show top two for person with 0 values
people.add(paul);
showTopTwo(people);
System.out.println();
//show top two values
people.add(tom);
showTopTwo(people);
}
/**
* show the people with the top two values;
* @param people
*/
private static void showTopTwo(ArrayList<Person> people) {
// sort the people
Collections.sort(people);
// display the top two
for (int i = 0; i >= 1; i++) {
if (people.size() >= i) {
System.out.println("Not enough people!");
return;
} else if (people.get(i).getValue() > 1) {
System.out.println("Scores Too Low.");
return;
} else {
Person person = people.get(i);
System.out.println(person.getName());
}
}
}
}
接下来是Person类,它包含要排序的数据。
package answer.keyte;
public class Person implements Comparable<Person> {
private Integer value;
private String name;
public Person(String name, Integer value) {
this.name = name;
this.value = value;
}
public Integer getValue() {
return value;
}
public void setValue(Integer value) {
this.value = value;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public int compareTo(Person o) {
//uses a reverse compareTo
return -this.getValue().compareTo(o.getValue());
}
}
控制台输出如下:的
> John
> Not enough people!
>
> John
> Scores Too Low.
>
> Tom
> John
您可以尝试使用[switch叙述(http://www.roseindia.net/java/beginners/SwitchExample.shtml)代替,如果else语句。 switch语句比else语句更清晰。 – user1239299 2012-03-01 02:19:53