為什么顯示超出范圍
import java.util.*;
public class HelloWorld {
? ??
? ? //完成 main 方法
? ? public static void main(String[] args) {
? ? ? int[] scores={89,-23,64,91,119,52,73};
? ? ? HelloWorld line = new HelloWorld();
? ? ? line.sort(scores);
? ? }
? ??
? ? //定義方法完成成績排序并輸出前三名的功能
? ? public void sort(int[]scores){
? ? //選出有效成績
? ? int i,j;?
? ? for(i=0,j=0;i<scores.length;i++);
? ? {
? ? ? ? if(scores[i]>0&&scores[i]<100)
? ? ? ? {
? ? ? ? ? ? scores[j]=scores[i];
? ? ? ? ? ? j++;
? ? ? ? }
? ? }
? ? //有效成績排序
? ? Arrays.sort(scores);
? ? System.out.println("考試前三名為:");
? ? //選出前三名
? ? for(int k=scores.length-1;k>scores.length-4;k--)
? ? {
? ? ? ? System.out.println(scores[k]);
? ? }
? ? }
? ??
運行顯示問題:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 7
at ad.HelloWorld.sort(HelloWorld.java:18)
at ad.HelloWorld.main(HelloWorld.java:9)
2016-06-02
根據(jù)數(shù)學(xué)上證明一個結(jié)論不能在證明時使用這個結(jié)論,類比到編程,認(rèn)為:在定義sort(int[] scores)時,應(yīng)該不能調(diào)用sort(scores)便把你的sort(int[] scores)方法改成了2個,就能輸出結(jié)果。不知道原因是不是這個,是這么想的,就做了相應(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};
? ? ? HelloWorld line = new HelloWorld();
? ? ? line.sort1(scores);
? ? }
? ??
? ? //定義方法完成成績排序并輸出前三名的功能
? ? public void sort(int[]scores){
? ? //選出有效成績
? ? int i,j;?
? ? for(i=0,j=0;i<scores.length;i++);
? ? {
? ? ? ? if(scores[i]>0&&scores[i]<100)
? ? ? ? {
? ? ? ? ? ? scores[j]=scores[i];
? ? ? ? ? ? j++;
? ? ? ? }
? ? }
? ? }
? ? public void sort1(int[] scores){
? ? //有效成績排序
? ? Arrays.sort(scores);
? ? System.out.println("考試前三名為:");
? ? //選出前三名
? ? for(int k=scores.length-1;k>scores.length-4;k--)
? ? {
? ? ? ? System.out.print(scores[k]+" ");
? ? }
? ? }
}
考試前三名為:
119 91 89?
2016-05-22
public void sort(int[] scores){
? ? ? ? int count=0;
? ? ? ? Arryas.sort(scores);
? ? ? ? for(int i=scores.length;i>=0;i--){
? ? ? ? ? ? if(scores[i]>0&&scores[i]<100){
? ? System.out.println(scores[i]);
count++;
if(count==3){
break;
}
}
? ? ? ? }
? ? }
這樣可以輸出前三名!你的情況我也出現(xiàn)過,不過我也不知道為什么
2016-05-22
我把輸出考試前三那行的println換成print了顯示下面這些
/85/1598/DsXg/HelloWorld.java:35: error: reached end of file while parsing
? ?}
? ? ^
1 error