如何得出前三名成績(jī)的呀?
我還是不懂,從后往前遍歷,當(dāng)遍歷到i=6,i=5,i=4位置時(shí),scores[i]分別等于52,64,73,此時(shí)num=3,再繼續(xù)遍歷num=4,退出了循環(huán),那輸出的不是52,64,73了?是怎么得出91,89,73的呀??
我還是不懂,從后往前遍歷,當(dāng)遍歷到i=6,i=5,i=4位置時(shí),scores[i]分別等于52,64,73,此時(shí)num=3,再繼續(xù)遍歷num=4,退出了循環(huán),那輸出的不是52,64,73了?是怎么得出91,89,73的呀??
2016-03-03
舉報(bào)
2016-03-06
Arrays.sort(scores)已經(jīng)把數(shù)組排序了,就是?{-23, 52, 64, 73, 89, 91, 119},而for(int i=scores.length;i>=0;i--)這個(gè)相當(dāng)于是吧已經(jīng)排序好的數(shù)組倒序遍歷也就是從{119,91,89,73,64,52,-23}這邊開(kāi)始數(shù),所以輸出的就是91,89,73
2016-03-05
public class HelloWorld {
import java.util.Arrays;
??? //完成 main 方法
??? public static void main(String[] args) {
??????? HelloWorld getGrades = new HelloWorld(); //創(chuàng)建對(duì)象getGrades
??? ?int[] result = getGrades.exam(89,-23,64,91,119,52,73);//調(diào)用對(duì)象并傳入?yún)?shù)
??? }
???
??? //定義方法完成成績(jī)排序并輸出前三名的功能
??? public int[] exam(int a,int b,int c,int d,int e,int f,int g){//構(gòu)造包含參數(shù)的exam方法
??? ?int[] scores = {a,b,c,d,e,f,g};//創(chuàng)建數(shù)組
??Arrays.sort(scores); //對(duì)數(shù)組進(jìn)行升序排序
??int effGra = 0; //定義并初始化有效成績(jī)個(gè)數(shù)
??for (int i = scores.length-1;i >= 0;i--){ //倒序遍歷數(shù)組
???if ((scores[i]<0)||(scores[i]>100)){ //如果成績(jī)小于 0 或大于 100
????continue;?????? //則使用 continue忽略此成績(jī)
???}
???effGra++; //有效成績(jī)+1
???if (effGra > 3){ //如果有效成績(jī)數(shù)大于 3
????break; //則結(jié)束循環(huán)
???}
???else{
????System.out.printf(scores[i]+"\t"); //只輸出成績(jī)的前三名
???}
??}
??return scores;
?}
}
2016-03-03
Arrays.sort() ?讓數(shù)列從小到大排列的,既int[] scores = {-23, 52, 64, 73, 89, 91, 119} ? ,scores[scores.length-1]=119,不滿足條件,結(jié)束本次循環(huán),而num也沒(méi)有變化,繼續(xù)下次循環(huán),當(dāng)滿足條件時(shí)候,num會(huì)加1,此時(shí)記錄下array[i],就是第一個(gè)數(shù)字,
2016-03-03
Arrays.sort() ?是讓數(shù)組升序排列,所以int[] scores = {-23, 52, 64, 73, 89, 91, 119} ??
雖然是從后往前遍歷,但是數(shù)組的下標(biāo)是從0-6來(lái)排的,所以scores[6]=119,scores[5]=91,依次類(lèi)推。