求解為什么是length-1
import java.util.Arrays;
public class HelloWorld {
?//完成main方法
?public static void main(String[] args) {
??System.out.println("考試成績(jī)的前三名為:");
??int[]score={89,-23,64,91,119,52,73};//成績(jī)組
??HelloWorld hello=new HelloWorld();//創(chuàng)建對(duì)象,對(duì)象名為hello
??hello.qiSan(score);//調(diào)用方法,傳入成績(jī)組
?}
?/*
? * 功能:輸出考試成績(jī)的前三名定義一個(gè)包含整形數(shù)組的方法,用來(lái)傳入成績(jī)數(shù)組
? */
?public void qiSan(int[]scores){
??Arrays.sort(scores);//使用Arrays.sort()方法實(shí)現(xiàn)數(shù)組排序
??int num=0;//保存有效成績(jī)的數(shù)量
??for(int i=scores.length-1;i>=0;i--){///倒序數(shù)組中的每一個(gè)元素
???if(scores[i]<0||scores[i]>100){//判斷成績(jī)有效性
????continue;//如果成績(jī)無(wú)效,則跳過(guò)本次循環(huán),忽略次成績(jī)
???}
???num++;//有效成績(jī)數(shù)加1
???if(num>3){//判斷有效成績(jī)的數(shù)量
????break;//如果有效成績(jī)大于3,則結(jié)束循環(huán),只輸出成績(jī)的前三名
???}
???System.out.println(scores[i]);//依次輸出成績(jī)前三名
2016-08-04
scores.length 表示 scores數(shù)組的長(zhǎng)度。數(shù)組的下標(biāo)是0開始到scores.length-1結(jié)束
2016-07-23
數(shù)組長(zhǎng)度為length,但數(shù)組下標(biāo)是從0開始,所以是length-1, 就是最后一個(gè)。
比如這里scores[]有6個(gè)元素,scores.length ==6, scores[5]就是第六個(gè)元素。
?hello.qiSan(score);//調(diào)用方法,傳入成績(jī)組-----你這里少了個(gè)s