亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定

程序輸出錯誤調試

8-1為何只輸出兩個數不是三個?

import java.util.*;

public class HelloWorld {

? ??

? ? //完成 main 方法

? ? public static void main(String[] args) {

? ? ? ? //定義數組

? ? ? ? int scores[]=new int []{89,-23,64,91,119,52,73};

? ? ? ? HelloWorld hello=new HelloWorld();

? ? ? ? hello.sort(scores);

? ? ? ??

? ? }

? ?

? ? //定義方法完成成績排序并輸出前三名的功能

? ? public void sort(int [] scores){

? ? ? ?Arrays.sort(scores);

? ? ? ?System.out.println("考試成績的前三名為:");

? ? ? ?for(int i=scores.length-1;i>=0&&i>=scores.length-3;i--){

? ? ? ? ? if(scores[i]>=0&&scores[i]<=100) {System.out.println(scores[i]);

? ? ? ?}

? ? ? ?

? ? }

?}

}


正在回答

3 回答

?private void sort(int []scores){

? ? ? ? Arrays.sort(scores);

? ? ? ? System.out.println("考試成績的前三名為:");

? ? ? ? for(int i = scores.length -1; i >-1 ;i--){

? ? ? ? ? ? if(scores[i] <0 || scores[i]>100)

? ? ? ? ? ? ? ? continue;

? ? ? ? ? ? else if(scores.length -1 -i < 4){

? ? ? ? ? ? ? ? System.out.println(scores[i]);

? ? ? ? ? ? }

? ? ? ? }?

? ? }


0 回復 有任何疑惑可以回復我~

數組排序后,變為[-23,52,64,73,89,91,119]。

第一次循環,i=6,scores[i]=119,不滿足boolean條件,不輸出;

第二次循環,i=5,scores[i]=91,輸出;

第三次循環,i=4,scores[i]=89,輸出;

第四次循環,i=3,此時i<4,不滿足條件,程序執行結束。

只有兩次是因為程序沒有使用計數器,而是直接篩選數組后三個,而這三個中又有一個不滿足輸出條件,因而只有兩個。

0 回復 有任何疑惑可以回復我~
?//4、?判斷成績的有效性,如果成績小于?0?或大于?100?,則使用?continue?忽略此成績
?//5、?如果成績有效,則有效成績數加?1?。判斷有效成績的個數,如果有效成績數大于?3?,則結束循環,只輸出成績的前三名
?
?if(scores[i]>0?&&?scores[i]<100){
????????????????count++;
????????????????if(count?>?3){
????????????????????break;
????????????????}else{
????????????????????System.out.println(scores[i]);?
????????????????}
????????????}else{
????????????????continue;
????????????}


0 回復 有任何疑惑可以回復我~

舉報

0/150
提交
取消

程序輸出錯誤調試

我要回答 關注問題
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號