エクササイズ:
(生徒の並べ替え) 生徒の人数、名前、点数を入力し、生徒名を点数の高い順に出力するプログラムを作成してください。
私がこれまでに行ったこと:
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;
}
}
エラー: スレッド「メイン」の例外 java.lang.ArrayIndexOutOfBoundsException: 3 at chapter6.Chapter6.displayNamesForScores(Chapter6.java:45) at chapter6.Chapter6.main(Chapter6.java:36) Java Result: 1
私はしばらく頭を悩ませてきましたが、理解できません。なぜこのエラーが発生するのでしょうか。お時間をいただきありがとうございます。答えを楽しみにしています。