為啥輸出的東西不對啊
public static void main(String[] args) {
? ? ? ? int[] scores={89,-23,64,91,119,52,73};
? ? ? ? HelloWorld hello = new HelloWorld();
? ? ? ? hello.youxiao(scores);
? ? ? ? hello.chengji(scores);
? ? }
? ? public void youxiao(int scores[]){
? ? ? ? int i=0;
? ? ? ? for(int score:scores)
? ? ? ? {
? ? ? ? ? ? if(score<100&&score>0)
? ? ? ? ? ? {
? ? ? ? ? ? scores[i]=score;
? ? ? ? ? ? i+=1;
? ? ? ? ? ? }
? ? ? ? }
? ? }
? ? public void chengji(int scores[]){
? ? ? ? Arrays.sort(scores);? ??
? ? ? ? for(int i=scores.length-3;i<scores.length;i++){
? ? ? ? ? ? System.out.println(scores[i]);
? ? ? ? }
? ? }
2018-08-01
輸出了什么東西
2018-08-02
你在main中hello.youxiao(scores);后添加一句System.out.println(Arrays.toString(scores));會發(fā)現(xiàn)scores數(shù)組已經(jīng)變成 [89, 64, 91, 52, 73, 52, 73];然后你再執(zhí)行?hello.chengji(scores)后又會排序,scores數(shù)組變成了,[52, 52, 64, 73, 73, 89, 91];所以你最后輸出的73,89,91。
你可以將youxiao中的改成,如下,將不符合的數(shù)據(jù)改成-1,這樣排序的時候不會影響正常數(shù)值的排序(因為排序是升序,-1都會在數(shù)組最前面),而且也不會改變數(shù)組的長度,所以你最后可以從數(shù)組的最后三個取到正確的值(這樣你就不用判斷數(shù)組的有效值究竟是第幾位到第幾位,只需從最后三個提取數(shù)值就ok)。
這是按照你的思路改的,但是實際上沒有必要寫這么麻煩的。。。你可以再自己考慮更好的思路
2018-08-02
i<scores.length;?
而且這句不對,i=4了,i又小于數(shù)組長度7,i--。這樣就是死循環(huán)了,因為 i 永遠(yuǎn)小于7
2018-08-02
2018-08-02
for(int i=scores.length-3;i<scores.length;i++)。這句,數(shù)組長度是7,7-3=4。下表從4開始,i--,依次往下輸出,輸出的元素是下表為[4][3][2][1][0]里的元素了,當(dāng)然不對了。你看看:
int temp = 0;
for(int i = (length-1); i>=0 && temp<3; i--) {
if(scores[i]<0 || scores[i]>100)
continue;
temp++;
System.out.println(scores[i]);
}
2018-08-01
if(score<100&&score>0)這里不可以是或 要兩者同時滿足