import java.util.Arrays;
public class showTop3 {
/**
* 1、 考試成績已保存在數組 scores 中,數組元素依次爲 89 , -23 , 64 , 91 , 119 , 52 , 73
*
* 2、 要求通過自定義方法來實現成績排名並輸出操作,將成績數組作爲參數傳入
*
* 3、 要求判斷成績的有效性( 0—100 ),如果成績無效,則忽略此成績
*
* @param args
*/
// 完成 main 方法
public static void main(String[] args) {
int[] scores = new int[] { 89, -23, 64, 91, 119, 52, 73 };
System.out.println("成績前三名:");
// 創建一個本類對象
showTop3 helloWorld = new showTop3();
// 調用showTop3()方法
helloWorld.Top3(scores);
}
// 定義方法完成成績排序並輸出前三名的功能
public void Top3(int[] scores) {
// 數組的排序
Arrays.sort(scores);
// 保存有效成績的個數
int okScores = 0;
// 倒序遍歷數組中的每一個元素
for (int i = scores.length - 1; i >= 0; i--) {
// 判斷成績的有效性
if (scores[i] < 0 || scores[i] > 100) {
// 如果成績無效,則跳過本次成績,忽略此成績
continue;
}
// 成績有效,有效成績個數+1
okScores++;
// 當有效成績大於3個的時候
if (okScores > 3) {
// 跳出遍歷循環
break;
}
// 依次輸出前三名的成績
System.out.println(scores[i]);
}
}
}
java入門--數組的排序案例:輸出成績前三名
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.