import java.util.Arrays;/**?* 實(shí)現(xiàn)輸出考試成績(jī)的前三名?* 要求:?* 1、 考試成績(jī)已保存在數(shù)組 scores 中,數(shù)組元素依次為 89 , -23 , 64 , 91 , 119 , 52 , 73?* 2、 要求通過(guò)自定義方法來(lái)實(shí)現(xiàn)成績(jī)排名并輸出操作,將成績(jī)數(shù)組作為參數(shù)傳入?* 3、 要求判斷成績(jī)的有效性( 0—100 ),如果成績(jī)無(wú)效,則忽略此成績(jī)*/public class HelloWorld { // 完成 main 方法 public static void main(String[] args) { int[] scores = { 89, -23, 64, 91, 119, 52, 73 };// 成績(jī)數(shù)組 System.out.println("考試成績(jī)的前三名為:"); HelloWorld hello = new HelloWorld();// hello對(duì)象 hello.scs(scores);// 調(diào)用scs方法 } // 定義方法完成成績(jī)排序并輸出前三名的功能 public void scs(int[] scores) { int count = 3; Arrays.sort(scores); for (int i = scores.length - 1; count > 0; i++) { if (scores[i] > 100 || scores[i] < 0) {// 不滿(mǎn)足條件1-100的成績(jī)跳出 continue; } else { count--; System.out.println(scores[i]);// 依次輸出前三名成績(jī) } } }}
2 回答
已采納

Tobey_滔
TA貢獻(xiàn)242條經(jīng)驗(yàn) 獲得超128個(gè)贊
錯(cuò)誤位置在csc函數(shù)的for循環(huán)中..for (int i = scores.length - 1; count > 0; i++) {}
你是從后往前遍歷的...不應(yīng)該i++...i++會(huì)出現(xiàn)越界的...改成i--即可
//?定義方法完成成績(jī)排序并輸出前三名的功能 public?void?scs(int[]?scores)?{ int?count?=?3; Arrays.sort(scores); for?(int?i?=?scores.length?-?1;?count?>=?0;?i--)?{ if?(scores[i]?>?100?||?scores[i]?<?0)?{//?不滿(mǎn)足條件1-100的成績(jī)跳出 continue; }?else?{ count--; System.out.println(scores[i]);//?依次輸出前三名成績(jī) } } }
還有count >= 0 ?下標(biāo)是從0開(kāi)始的...你不等于0就會(huì)少對(duì)一個(gè)元素進(jìn)行判斷哦
添加回答
舉報(bào)
0/150
提交
取消