package?com.imooc;
import?java.util.Arrays;
import?java.util.Scanner;
public?class?HelloWorld?{
public?static?void?main(String[]?args){
int[]?score?=?new?int[6];
HelloWorld?hello?=?new?HelloWorld();
Scanner?input?=?new?Scanner(System.in);
for(int?i=0;i<6;i++){
System.out.print("請(qǐng)輸入第"+(i+1)+"個(gè)人的成績:");
score[i]?=?input.nextInt();
}
String?result?=?hello.getTop3(score);
System.out.println("前三名的成績?yōu)椋?+result);
}
/**
?*?求所有考試成績中的前三名
?*?@return?前三名的成績
?*/
public?String?getTop3(int[]?score){
int[]?top3?=?new?int[3];
int?j?=?0;
Arrays.sort(score);
for(int?i=score.length-1;i>score.length-4;i--){
if(score[i]?>100?||?score[i]?<?0)?continue;
top3[j++]?=?score[i];
}
return?Arrays.toString(top3);
}
}
2016-12-01
for(int?i=score.length-1;i>score.length-4;i--){
????????????if(score[i]?>100?||?score[i]?<?0)?continue;
????????????top3[j++]?=?score[i];
????????}
你問題出在 ??i>score.length-4 ? 這里,
你運(yùn)行你的代碼可以發(fā)現(xiàn)你如果輸入的數(shù)字全部符合1~100的范圍的話,程序可以正確運(yùn)行。
問題就是,你sort(score)之后,你for遍歷的只有倒數(shù)的那三個(gè)分?jǐn)?shù),而如果其中一個(gè)分?jǐn)?shù)超過了100分的話,超過100的那個(gè)分?jǐn)?shù)被continue掉了,然后你遍歷的數(shù)就只剩兩個(gè)數(shù)了,所以結(jié)果就會(huì)顯示類似'''前三名的成績?yōu)椋篬100, 90, 0]'''之類的情況了。