package j2.lesson01_2;
public class ExamRecordAction5 {
public static void main(String[] args) {
ExamRecord[] rec = new ExamRecord[4];
rec[0] = createExamRecord("Taro", 50, 90, 100);
rec[1] = createExamRecord("Hanako", 70, 30, 80);
rec[2] = createExamRecord("Kenji", 60, 50, 70);
rec[3] = createExamRecord("Aya", 40, 100, 90);
showExamRecords(rec);
System.out.println("===数学の点数順に並べると===");
sortByMath(rec);
showExamRecords(rec);
System.out.println("===3科目平均点の順に並べると===");
sortByAverage(rec);
showExamRecords(rec);
}
public static ExamRecord createExamRecord(String name,
int math, int japanese, int english) {
ExamRecord r = new ExamRecord();
r.name = name;
r.math = math;
r.japanese = japanese;
r.english = english;
return r;
}
public static void showExamRecord(ExamRecord r) {
System.out.println(r.name + ", 数学 = " + r.math
+ ", 国語 = " + r.japanese
+ ", 英語 = " + r.english
+ ", 3科目の平均 = "
+ ((r.math + r.japanese + r.english) / 3.0));
}
public static void showExamRecords(ExamRecord[] ra){
for(int i=0; i<ra.length; i++){
showExamRecord(ra[i]);
}
}
public static double averageMath(ExamRecord[] ra){
int sum = 0;
for(int i=0; i<ra.length; i++){
sum += ra[i].math;
}
return (double)sum / ra.length;
}
public static double averageJapanese(ExamRecord[] ra){
int sum = 0;
for(int i=0; i<ra.length; i++){
sum += ra[i].japanese;
}
return (double)sum / ra.length;
}
public static double averageEnglish(ExamRecord[] ra){
int sum = 0;
for(int i=0; i<ra.length; i++){
sum += ra[i].english;
}
return (double)sum / ra.length;
}
public static double getAverage(ExamRecord r){
return (r.math + r.japanese + r.english)/3.0;
}
public static void sortByMath(ExamRecord[] ra){
boolean changed = true;
while(changed){
changed = false;
for(int i=0; i<=ra.length-2; i++){
if(ra[i].math < ra[i+1].math){
ExamRecord temp = ra[i];
ra[i] = ra[i+1];
ra[i+1] = temp;
changed = true;
}
}
}
}
public static void sortByAverage(ExamRecord[] ra){
boolean changed = true;
while(changed){
changed = false;
for(int i=0; i<=ra.length-2; i++){
if(getAverage(ra[i])< getAverage(ra[i+1])){
ExamRecord temp = ra[i];
ra[i] = ra[i+1];
ra[i+1] = temp;
changed = true;
}
}
}
}
}
|