import java.util.Arrays;public class HelloWorld {? ??? ? //完成 main 方法? ? public static void main(String[] args) {? ? ? ? int [] scores={89,-23,64,91,119,52,73};? ? ? ? System.out.println("考試成績的前三名為:");? ? ? ? HelloWorld hello=new HelloWorld();? ? ? ? hello.showTOP3(scores);? ? ? ??? ? }? ??? ? //定義方法完成成績排序并輸出前三名的功能? ? public void showTOP3(int scores[]){? ? ? ? int count=0;? ? ? ? Arrays.sort(scores);? ? ? ? for(int i=scores.length-1;i>=0;i++){? ? ? ? ? ? if(scores[i]<0||scores[i]>100){? ? ? ? ? ? ? ? continue;? ? ? ? ? ? }? ? ? ? ? ? else{? ? ? ? ? ? ? ? System.out.println(scores[i]);? ? ? ? ? ? ? ? count++;? ? ? ? ? ? }? ? ? ? ? ? if(count>3)? ? ? ? ? ? break;? ? ? ? }? ? }}
3 回答

chandou
TA貢獻22條經(jīng)驗 獲得超11個贊
1、首先注意你的編碼規(guī)范,不知道是不是貼代碼的沒注意還是什么情況,有點混亂,良好的編碼規(guī)范是十分重要的;
2、如果單純的解決你這段程序的BUG,只要把for循環(huán)中的i++,更改為i--即可,初始化i賦值為數(shù)組的長度-1,如果在i++,就會報數(shù)組下標(biāo)越界的錯誤;
3、只更改i--,最終也不會實現(xiàn)你想要的獲取前三名的目的,這就得看你邏輯思考了,建議問題需要自己思考解決,跑下程序就很清晰了。

皮縣豆福腦
TA貢獻18條經(jīng)驗 獲得超4個贊
首先上傳代碼的時候可以選擇代碼語言,然后發(fā)布出來就是有格式的代碼;接下來說說你遇到的問題:
問題有兩點
循環(huán)條件中應(yīng)為i--
????????你使用Arrays類的sort( )方法對數(shù)組進行排序,默認(rèn)按升序排列,由于要輸出的是前三名成績,所以從后往前遍歷,即倒序遍歷。
????2.終止條件應(yīng)為count==3
????????判斷有效成績的個數(shù),如果有效成績數(shù)等于3 ,則結(jié)束循環(huán),只輸出成績的前三名。
綜上,正確的代碼應(yīng)該是
import?java.util.Arrays; public?class?HelloWorld?{ ????//?完成?main?方法 ????public?static?void?main(String[]?args)?{ ????????int[]?scores?=?{?89,?-23,?64,?91,?119,?52,?73?}; ????????System.out.println("考試成績的前三名為:"); ????????HelloWorld?hello?=?new?HelloWorld(); ????????hello.showTOP3(scores); ????} ????//?定義方法完成成績排序并輸出前三名的功能 ????public?void?showTOP3(int?scores[])?{ ????????int?count?=?0; ????????Arrays.sort(scores); ????????for?(int?i?=?scores.length?-?1;?i?>=?0;?i++)?{ ????????????//若進入循環(huán)不是有效的成績時,跳過這個成績 ????????????if?(scores[i]?<?0?||?scores[i]?>?100)?{ ????????????????continue; ????????????} ????????????else?{ ????????????????System.out.println(scores[i]); ????????????????count++; ????????????} ????????????//累計輸出的分?jǐn)?shù)個數(shù)為3時,中止循環(huán) ????????????if?(count?==?3) ????????????break; ????????} ????} }
希望可以幫到你~
添加回答
舉報
0/150
提交
取消