要求
1、 考試成績已保存在數組 scores 中,數組元素依次爲 89 , -23 , 64 , 91 , 119 , 52 , 73
2、 要求通過自定義方法來實現成績排名並輸出操作,將成績數組作爲參數傳入
3、 要求判斷成績的有效性( 0—100 ),如果成績無效,則忽略此成績
提示:
1、 在方法中使用 Arrays 類的 sort( ) 方法對數組進行排序,默認按升序排列,注意 Arrays 類的使用需要導入 java.util.Arrays
2、 由於只需要輸出考試成績的前三名,所以定義一個變量,統計有效成績的前三名的數量
3、 使用 for 循環遍歷數組中的元素,由於要輸出的是前三名成績,所以從後往前遍歷,即倒序遍歷 如 for ( int i = scores.length - 1; i >= 0; i-- ) { }
4、 判斷成績的有效性,如果成績小於 0 或大於 100 ,則使用 continue 忽略此成績
5、 如果成績有效,則有效成績數加 1 。判斷有效成績的個數,如果有效成績數大於 3 ,則結束循環,只輸出成績的前三名
import java.util.Arrays;
public class HelloWorld {
//完成 main 方法
public static void main(String[] args) {
int [] scores={89,-23,64,91,119,52,73};
System.out.println("考試成績的前三名爲:");
HelloWorld hello=new HelloWorld();
hello.showTop3(scores);
}
//定義方法完成成績排序並輸出前三名的功能
public void showTop3(int[] scores){
Arrays.sort(scores);
int num=0; //記錄有效成績的個數
//輸出前三名
for(int i=scores.length-1;i>=0;i--){
//判斷成績是否有效
if(scores[i]<0 || scores[i]>100){
continue;
}
num++;
if(num>3)
break;
System.out.println(scores[i]);
}
}
}