これは、ユーザーの帰属評点を取得し、その平均、偏差を見つけて、この情報を表形式で表示するためのコードです。私のプログラムはユーザー入力を受け取り、情報を適切に表示しますが、平均と偏差を正しく計算しません。実行すると、平均が 0 と表示されます。先生が教えてくれたのと同じように実行していますが、エラーが見つかりません。
import java.util.Scanner;
public class ClassScores{
public static void main(String[] args){
String[] names = {"Bashful","Doc","Dopey","Grumpy","Happy","Sleepy","Sneezy"};
double[] grades = new double[7];
double mean=0;
double[] difference = new double[7];
getScores(grades);
average(grades, mean);
deviation(grades,mean,difference);
displayResults(names, grades, difference, mean);
}
public static double[] getScores(double[] grades)
{
Scanner kb= new Scanner(System.in);
System.out.println("Enter grades for students in alphabetical order.");
for (int i=0;i<grades.length; i++)
{
grades[i]=kb.nextDouble();
}
return grades;
}
public static double average(double[] grades, double mean)
{
double total = 0;
for (double i : grades)
{
total += i;
}
if (grades.length>0)
{
mean = total/grades.length;
}
return mean;
}
public static double[] deviation(double[] grades, double mean, double[] difference)
{
for (int i=0; i<grades.length; i++)
{
difference[i]=grades[i]-mean;
}
return difference;
}
public static void displayResults(String[] names, double[] grades, double[] difference, double mean)
{
System.out.println("The average score is" +mean);
System.out.println("Student Name Grade Mean Deviation");
for (int i=0; i<names.length; i++)
{
System.out.printf(names[i]);
System.out.printf("%20f", grades[i]);
System.out.printf("%20f", difference[i]);
System.out.println();
}
}
}
興味のある方のために編集したコードを次に示します。
java.util.Scanner をインポートします。
public class ClassScores{
public static void main(String[] args){
String[] names = {"Bashful","Doc","Dopey","Grumpy","Happy","Sleepy","Sneezy"};
double[] grades = new double[7];
double mean=0;
double[] difference = new double[7];
getScores(grades);
mean = average(grades);
deviation(grades,mean,difference);
displayResults(names, grades, difference, mean);
}
public static double[] getScores(double[] grades)
{
Scanner kb= new Scanner(System.in);
System.out.println("Enter grades for students in alphabetical order.");
for (int i=0;i<grades.length; i++)
{
grades[i]=kb.nextDouble();
}
return grades;
}
public static double average(double[] grades)
{
double total = 0;
for (double i : grades)
{
total += i;
}
return total/(grades.length);
}
public static double[] deviation(double[] grades, double mean, double[] difference)
{
for (int i=0; i<grades.length; i++)
{
difference[i]=grades[i]-mean;
}
return difference;
}
public static void displayResults(String[] names, double[] grades, double[] difference, double mean)
{
System.out.println("The average score is" +mean);
System.out.println("Student Name Grade Mean Deviation");
for (int i=0; i<names.length; i++)
{
System.out.printf(names[i]);
System.out.printf("%20f", grades[i]);
System.out.printf("%20f", difference[i]);
System.out.println();
}
}
}