キーボード入力された数字から最大値・最小値・平均値・偏差値を求める、配列を使ったプログラムを作成したいのですが...
コンパイルをなんとかクリアし、最大値・最小値・平均値までは正確に出力されたのですが、偏差値が出力されない代わりにArrayIndexOutOfBoundsExceptionが表示されました。
要素数の上限を1001個にしているにもかかわらず、どうしてこのエラーが出るのか分かりません。
java
1public class StandardScore{ 2 public static void main(String[] args){ 3 Scanner kbd=new Scanner(System.in); 4 int[] data=new int[1000]; 5 int min,max;//(左から)最小値、最大値 6 double ave;//平均値 7 int n=0; 8 System.out.println("数字を入力してください"); 9 10 //最小値・最大値・平均値- - - - - - - - - - - - - - - - - - - - - - 11 12 while(kbd.hasNext()){//hasNext()はリストに要素がなくなるまでtrueを返す 13 data[n]=kbd.nextInt(); 14 n++; 15 } 16 if(n == 0){ 17 System.out.println("データがありません"); 18 }else{ 19 int sum = 0; 20 min = max = data[0]; 21 for(int i = 0; i < n; i++){ 22 if(data[i] < min){ 23 min = data[i]; 24 } 25 if(data[i] > max){ 26 max = data[i]; 27 } 28 sum += data[i]; 29 } 30 ave =1.0*sum/n; 31 System.out.printf("min="+min); 32 System.out.printf("max="+max); 33 System.out.printf("ave="+ave); 34 35 //標準偏差sigma - - - - - - - - - - - - - - - - - - - - - - - - - 36 37 double sigma=0; 38 for(int i=0;i<n;i++){ 39 sigma+=(data[n]-ave)*(data[n]-ave); 40 } 41 sigma/=n; 42 sigma=sqrt(sigma); 43 44 //偏差値hensachi- - - - - - - - - - - - - - - - - - - - - - - - - 45 46 double[] hensachi=new double[n]; 47 48 for(int i=0;i<n; i++){ 49 hensachi[n]=(data[n]-ave)*10/sigma+50; 50 System.out.printf("Standard Score of "+n+" is "+hensachi[n]); 51 } 52 } 53 } 54} 55
※10,20,30,40と入力しました
実行結果
min=10max=40ave=25.0
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4
at StandardScore.main(StandardScore.java:53)
どなたかエラーの具体的な原因を教えてください。
よろしくお願いします。
回答2件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
退会済みユーザー
2017/09/08 05:44
2017/09/08 05:46