java數(shù)組溢出,求解
java數(shù)組溢出的問(wèn)題
import java.util.Arrays;
public class HelloWorld {
? ??
? ? //完成 main 方法
? ? public static void main(String[] args) {
? ? ? ??
? ? ? ? int[] scores = {89,-23,64,91,119,52,73};
? ? ? ? HelloWorld hello = new HelloWorld();
? ? ? ? ?
? ? ? ?
? ? ? ? System.out.println("考試成績(jī)的前三名為");
? ? ? ? ?hello.paixu(scores);
? ? ? ??
? ? ? ??
? ? }
? ??
? ? //定義方法完成成績(jī)排序并輸出前三名的功能
? ??
? ??
? ? public void paixu(int[] scores){
? ? ? ? Arrays.sort(scores);
? ? ? ? int count = 0;
? ? ? ??
? ? ? ??
? ? ? ? for(int i=scores.length;i>0;i-- ){
? ? ? ? ? ? if(scores[i]<0||scores[i]>100){
? ? ? ? ? ? ? ? continue;
? ? ? ? ? ? }
? ? ? ? ? ??
? ? ? ? ? ? ? count++;
? ? ? ? ? ? if(count>3){
? ? ? ? ? ? ? ? break;
? ? ? ? ? ? }
? ? ? ? ? ? ? ??
? ? ? ? ? ?System.out.println(scores[i]);
? ? ? ? ? ? ? ? }
? ? ? ? ? ? ? ? ? ? }
? ? ? ??
? ? ? ? ? ? ? ? ? ? ? ? ? ? } ? 請(qǐng)問(wèn)這樣寫(xiě)那個(gè)for循環(huán)為什么會(huì)出現(xiàn)數(shù)組溢出,而要寫(xiě)成i=scores.length-1;i>=0;i--
2016-09-09
舉個(gè)例子,你定一個(gè)一個(gè)數(shù)組
int?? a = new? int? [3]????? 那么a.length =3;??? 元素是a[0]?? ,?? a[1]?? ,??? a[2]??? ;?? 并沒(méi)有a【3】,正確代碼如圖
只要減一下就好,望采納
2016-09-09
同學(xué)。以為數(shù)組是從0開(kāi)始排序的,即scores[0]~scores[length-1]工length個(gè)元素。
求采納