我在這裏是新來的,並決定開始回答較簡單的問題來幫助練習我的編碼技巧......這是我的解決方案,基於傑羅姆的建議。
雖然有點冗長,但我認爲它足夠靈活,可以滿足任何變化,例如需要更多人員或不同的排序標準。
首先是主程序。它包含一個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