我的代碼大家參考
import java.util.Arrays;
public class HelloWorld {
? ??
? ? //完成 main 方法
? ? public static void main(String[] args) {
? ? ? ? int[] scores={89,-23,64,91,119,52,-33,73};
? ? ? ? Arrays.sort(scores);
? ? ? ? ?HelloWorld hello=new HelloWorld();
? ? ? ? ?hello.topThree(scores);
? ? ? ??
? ? ? ??
? ? }
? ??
? ? //定義方法完成成績排序并輸出前三名的功能
? ? public void topThree(int[] scores){
? ? ? ? int count=0;
? ? ? ? for(int i=scores.length-1;i>=0;i--){
? ? ? ? ? ? if(count==3){
? ? ? ? ? ? ? ? break;
? ? ? ? ? ? }
? ? ? ? ? ? if(scores[i]<0||scores[i]>100){
? ? ? ? ? ? ? ? continue;
? ? ? ? ? ? }else{
? ? ? ? ? ? ? ? System.out.println(scores[i]);
? ? ? ? ? ? ? ? count++;
? ? ? ? ? ? ? ??
? ? ? ? ? ? }
? ? ? ? }
? ? ??
? ? }
2018-09-26
import java.util.Arrays;
public class HelloWorld {
? ??
? ? //完成 main 方法
? ? public static void main(String[] args) {
? ? ? ? int[] scores = {89 , -23 , 64 , 91 , 119 , 52 , 73};
? ? ? ? int validNumber = 3; // 獲取前三名
? ? ? ? HelloWorld hello = new HelloWorld();
? ? ? ? hello.getRanking(scores, validNumber);
? ? }
? ? //定義方法完成成績排序并輸出前三名的功能
? ? public void getRanking(int[] scores, int validNumber) {
? ? ? ? Arrays.sort(scores);
? ? ? ? for (int i = (scores.length - 1); i >= 0; i--) {
? ? ? ? ? ? if (scores[i] < 0 || scores[i] > 100) {
? ? ? ? ? ? ? ? continue;? ? ? ? ? ??
????????????}
? ? ? ? ? ? if (validNumber == 0) {
? ? ? ? ? ? ? ? break;
? ? ? ? ? ? }
? ? ? ? ? ? validNumber--;
? ? ? ? ? ? System.out.println(scores[i]);
? ? ? ? }
? ? }? ??
}
// 因為考慮的擴展性,getRanking獲取名次方法中多傳了一個參數(shù)。將來隨便想獲取前幾名都可以。