Reputation: 81
public class main {
public static void main(String[] args) {
aboveAverageTester();
}
public static int aboveAverage(int a, int b, int c, int d, int e, int f) {
//This method computes the average of the parameters
//and then returns how many of the parameters are above the average.
int avg = (a + b + c + d + e + f) / 6;
int above = 0;
if (a > avg) {
return a;
}else if (b > avg) {
return b;
}else if (c > avg) {
return c;
}else if (d > avg) {
return d;
}else if (e > avg) {
return e;
}else if (f > avg) {
return f;
}else{
return a + b + c + e + f;
}
}
public static int aboveAverageTester() {
int aboveAverage = aboveAverage(10, 10, 10, 10, 45, 50);
System.out.println(aboveAverage);
return aboveAverage;
}
}
I know the aboveAverage method logic may be completely off, but I'm getting a problem when I'm trying to return how many of the parameters are above the average.
From my code, I believe that when you keep returning like a, b ,c.. etc after each if-- it's just 1 instance and not adding to the list of others that my be larger than the average.
I'm trying to preform this without printing anything in this method, only logic.
I know I kind of messed up, also, at the bottom of the aboveAvg method by adding all the a,b,c,d,e,f and not just creating a list from them.
Can anyone give me an idea of how to approach this?
Upvotes: 3
Views: 230
Reputation: 131376
To count the number of elements above the average, you can loop on each one and increment a counter as the condition is true
:
int aboveAverage = 0;
List<Integer> numbers = Arrays.asList(a,b,c,d,e,f);
for (int number : numbers){
if (number > avg){
aboveAverage++;
}
}
return aboveAverage;
With Java 8, you could write it in a less verbose way :
long aboveAverage = Arrays.asList(a,b,c,d,e,f).stream()
.filter(n-> n > avg)
.count();
Upvotes: 1
Reputation: 170
Not sure if I got your question completely, but I guess you want to count how many values are above the average.
So instead of returning the value when the if statement holds true, you should increment the counter like this:
if (a > avg) {
above++;
}
Upvotes: 0
Reputation: 726619
Your method is returning one of the values, not the count. It also truncates the average when the sum a + b + c + d + e + f
is not divisible by six.
You can fix this by using double
for the average, dividing by 6.0
to force double
result type, and then counting the number of above average numbers with conditional operator:
double avg = (a + b + c + d + e + f) / 6.0;
return (a > avg ? 1 : 0)
+ (b > avg ? 1 : 0)
+ (c > avg ? 1 : 0)
+ (d > avg ? 1 : 0)
+ (e > avg ? 1 : 0)
+ (f > avg ? 1 : 0);
Upvotes: 1