Reputation: 336
I have
public int average(int grades[]){return **}
and I call it with: average({80, 90, 100})
I want to separate the array into three individual ints.
Upvotes: 1
Views: 76
Reputation: 9041
The fact that the data is in an array
, you already have "n" individual int
s. Each element of the array is an individual int
that you can access via an index value ranging from 0 to (n - 1), where n is the length of the array.
So an array of 3 int
s would have indices 0, 1, 2.
With that, if your average()
is to compute the average of the int
s you have in your array
, just loop through your array and accumulate the values into a sum and divide that sum by the number of int
s that you have.
public static void main(String[] args) throws Exception {
System.out.println("Average: " + average(new int[] {80, 90, 100}));
}
public static int average(int[] grades) {
int sum = 0;
for (int i = 0; i < grades.length; i++) {
sum += grades[i];
}
return sum / grades.length;
}
Results:
Average: 90
Upvotes: 0
Reputation: 752
If you're looking to compute the average of several integers in your grades array, as is implied by the name of your method, and regardless of how many items are in the array, you can use Java 8 streams. Just a suggestion.
public int average(int[] grades)
{
OptionalDouble od = Arrays.stream(grades).average();
if(od.isPresent())
{
return (int)od.getAsDouble();
}
return 0; //error condition to be checked by calling method.
}
Upvotes: 0
Reputation: 121
public int average1 = average[0];
public int average2 = average[1];
public int average3 = average[2];
Hope i helped :) Edit: Whoops forgot to put a semicolon xD
Upvotes: 3