0

锻炼:

(对学生进行排序)编写一个程序,提示用户输入学生人数、学生姓名和分数,并按分数降序打印学生姓名。

到目前为止我做了什么:

package chapter6;
import java.util.Scanner;

public class Chapter6 {


public static void main(String[] args) {

    /*6.17*/    
    //prompt the user to enter the number of students
    Scanner input = new Scanner(System.in);
    System.out.print("Please enter the student number ="+" ");
    int number = input.nextInt();

    //array for the names and input
    String[] names = namesInput(number);
    //array for scores and input
    double[] score = scoreInput(number);

    //display students' names in decreasing order according to theri scores
    displayNamesForScores(names,score,number);

}

public static void displayNamesForScores(String[] name,double[] score ,int number)
{   
    for(int i =0;i<number;i++)
        {double temp=0;
         String str ;
         if(score[i+1]>score[i])
         {   temp = score[i];
             score[i]=score[i+1];
             score[i+1]=temp;

             str = name[i];
             name[i]=name[i+1];
             name[i+1]= str;

         }


        }
   System.out.println("Students:");
   for(int i=0;i<number;i++)
       {
         System.out.println(name[i]+" ");
       }

}

public static double[] scoreInput(int number)
{
Scanner input = new Scanner(System.in);
double[] score = new double[number];
 int cnt=1;
for(int i =0;i<score.length;i++)
    {

    System.out.print("Please enter the score for the"+" "+cnt+" "+"student="+" ");
    double scr = input.nextDouble();
    score[i]=scr;
    cnt++;

    }    

return score;
}

public static String[] namesInput(int number)

{
   Scanner input = new Scanner(System.in);
   String[] name = new String[number];
   int cnt=1;
   for(int i= 0;i<name.length;i++)

        {

        System.out.print("Enter the"+" "+cnt+" "+"name ="+" ");
        String str = input.nextLine();
        name[i]=str;
        cnt++;
        }

 return name;
  }
 }

并且错误:线程“main”中的异常 java.lang.ArrayIndexOutOfBoundsException: 3 at chapter6.Chapter6.displayNamesForScores(Chapter6.java:45) at chapter6.Chapter6.main(Chapter6.java:36) Java 结果:1

我一直在抨击我的头一段时间,但无法弄清楚,为什么我会收到这个错误。谢谢你的时间,我期待着一个答案。

4

1 回答 1

4

你会ArrayIndexOutOfBoundsException在这条线上得到

if(score[i+1]>score[i]) // when i = number -1

因为当i = number - 1,i + 1等于number并且该索引在数组中不可访问。数组的最大可访问索引始终为array.length - 1。超出此范围的任何内容都会抛出ArrayIndexOutOfBoundsException.

于 2013-11-14T04:43:45.293 回答