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