感覺邏輯對的呀,實在找不出錯誤啊..........
import java.util.Arrays;
public class HelloWorld {
? ??
? ? //完成 main 方法
? ? public static void main(String[] args) {
? ? ? ?int[] scores = {89,-23,64,91,119,52,73};?
? ? ? ?HellWorld hello =new HelloWorld();?
? ? ? ?System.out.println("考試成績前三名為:");
? ? ? ?hello.rank(scores);
? ? ? ??
? ? }
}
? ??
? ? //定義方法完成成績排序并輸出前三名的功能
? ? public void rank(int[] scores){
? ? ? ? Arrays.sort(scores);
? ? ? ? int num = 0;
? ? ? ? while(num<3){
? ? ? ? ? ? for(int i=scores.length-1;i>0;i--){
? ? ? ? ? ? ? ? if(scores[i]>=0&&scores[i]<=100){
? ? ? ? ? ? ? ? ? ? System.out.println(scores[i]);
? ? ? ? ? ? ? ? ? ? num++;
? ? ? ? ? ? ? ? }
? ? ? ? ? ? }
? ? ? ? }
? ? }
?
2018-07-12
2018-06-23
你的循環(huán)是錯的。
當(dāng)你的for循環(huán)做完后, 你的num 肯定是大于3 的了。
因為是要先做for循環(huán),當(dāng)你的scores 是100 和0 之內(nèi), 打印出score[i] , 并且Num ++ , 做完這個循環(huán)之后檢查while循環(huán), 所以你就會打印出全部的Scores了。?
我的代碼:
import java.util.Arrays;
public class HelloWorld {
? ? //完成 main 方法
? ? public static void main(String[] args)?
? ? {
? ? ? ? int scores[]= {89 , -23 , 64 , 91 , 119 , 52 , 73};? ??
? ? ? ? HelloWorld a = new HelloWorld();
? ? ? ??
? ? ? ? System.out.println("The top three grades of this exam are: ");
? ? ? ??
? ? ? ? Arrays.sort(scores);
? ? ? ? a.sort(scores);
? ? ? ??
? ? }
? ??
? ? //定義方法完成成績排序并輸出前三名的功能
? ? void sort(int scores[])
? ? {
? ? ? ? int available = 1;
? ? ? ? for(int element = scores.length -1 ; element>= 0 ; element--)
? ? ? ? {
? ? ? ? ? ? if(scores[element] < 0 || scores[element]>100)
? ? ? ? ? ? {?
? ? ? ? ? ? ? ? continue;
? ? ? ? ? ? }
? ? ? ? ? ??
? ? ? ? ? ? System.out.println(scores[element]);
? ? ? ? ? ? available++;
? ? ? ? ? ??
? ? ? ? ? ? if(available > 3)
? ? ? ? ? ? {
? ? ? ? ? ? ? ? break;
? ? ? ? ? ? }
? ? ? ? }
? ? }