So I have a program that will calculate grade average, highest grade, lowest grade, and an average without the lowest grade. So for my method that determines the new average without the lowest grade I would like to use the lowest grade I already found within that method.
/**
* lowestGrade() - method will return lowest grade
* @return lowGrade
*/
public static double lowestGrade(double[] grades) {
double lowGrade = 100.0;
// for loop that goes through grades array and stores
// first grade found as highest grade
for (int i = 0; i < grades.length; i++) {
// if statement will determine true lowest grade
if ( grades[i] < lowGrade ) {
lowGrade = grades[i];
}
}
// Output
return lowGrade;
}
/**
* averageWOLowGrade() - method will calculate average without lowest grade
* @return newAverage
*/
public static void averageWOLowGrade(double[] grades) {
double newAverage = 0;
}
As mentioned before , you can store the lowest grade in a field:
private static double min = 0.0;
public static double lowestGrade(double[] grades) {
// Set min and return its value.
return min = DoubleStream.of(grades).min().getAsDouble();
}
public static double averageWOLowGrade(double[] grades) {
return DoubleStream.of(grades).filter(x -> x != min)
.average()
.getAsDouble();
}
Bear in mind that order of execution matters here. I'd rather calculate the value twice instead of managing state in a static variable. Or even better: calculate all results in one run:
public static Stats computeStats(double[] grades) {
double min, max;
min = max = grades[0];
double sum = 0.0;
for (double grade : grades) {
if (grade < min) {
min = grade;
} else if (grade > max) {
max = grade;
}
sum += grade;
}
double avg = sum / grades.length;
int len = 0;
sum = 0.0;
for (double grade : grades) {
if (grade != min) {
sum += grade;
len++;
}
}
return new Stats(min, max, avg, sum / len);
}
static class Stats {
public final double min;
public final double max;
public final double avg;
public final double avgWithoutMin;
Stats(double min, double max, double avg, double avgWithoutMin) {
this.min = min;
this.max = max;
this.avg = avg;
this.avgWithoutMin = avgWithoutMin;
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.