9

I have a homework assignment and I was wondering if anyone could help me as I am new to Java and programming and am stuck on a question. The question is:

The first method finds the average of the elements of an integer array:

public double average(int[] data)

That is, given an integer array, data, calculate the average of its elements are return the average value. For example, the average of {1, 3, 2, 5, 8} is 3.8.

Here is what I have done so far:

public double average(int[] data) {  
    int sum = 0;

    while(int i=0; i < data.length; i++) 

    sum = sum + data[i]; 
    double average = sum / data.length;; 

    System.out.println("Average value of array element is " " + average);
}

When compiling it I get an error message at the int i=0 part saying '.class expected'. Any help would be appreciated.

Andrzej Doyle
  • 102,507
  • 33
  • 189
  • 228
user1605782
  • 111
  • 1
  • 2
  • 8
  • 2
    @DanglingPiyush No need to. The question is clear. – Marko Topolnik Aug 17 '12 at 08:31
  • 2
    Your whitespace is quite misleading. It's usually considered good practice to use braces around for/while loops for clarity, whereas what you have now is misleading. See [this pastebin](http://pastebin.com/HLpFv8zw) for an example of what I mean. – Andrzej Doyle Aug 17 '12 at 08:34

8 Answers8

18

Using an enhanced for would be even nicer:

int sum = 0;
for (int d : data) sum += d;

Another thing that will probably give you a big surprise is the wrong result that you will obtain from

double average = sum / data.length;

Reason: on the right-hand side you have integer division and Java will not automatically promote it to floating-point division. It will calculate the integer quotient of sum/data.length and only then promote that integer to a double. A solution would be

double average = 1.0d * sum / data.length;

This will force the dividend into a double, which will automatically propagate to the divisor.

Marko Topolnik
  • 195,646
  • 29
  • 319
  • 436
  • 2
    And one can fix the integer division problem either by assigning `sum` as a `double` initially; or by explicitly casting either of the arguments on the division line, e.g. `double average = ((double)sum) / data.length;` – Andrzej Doyle Aug 17 '12 at 08:36
  • 1
    @AndrzejDoyle I wouldn't recommend `double sum` as a general solution as it will lead to precision loss for integers above 2^54 (or was it 2^56?). Anyway, a quite large number, but still, why do it when there's a cleaner alternative. – Marko Topolnik Aug 17 '12 at 08:38
  • Agreed, converting before division is the "proper" way to do it. (I think in your example I'd want to add brackets, to make it clear that it's evaluated as `(1.0d * sum) / data.length` and not `1.0d * (sum / data.length)`, as the latter is still wrong. I realise that even without brackets Java will take the former approach, but the brackets are a sort of documentation that will remove any doubt for someone reading. A bit like marking variables `final` even if they're never actually reassigned.) – Andrzej Doyle Aug 17 '12 at 08:44
  • @AndrzejDoyle I kind of dislike the parens, but if I did use them, I'd go with your suggestion: `((double)sum)/data.length` since it makes the intention even more clear and direct, not to say possibly shaves off an unneeded FP operation. – Marko Topolnik Aug 17 '12 at 08:47
  • You should also be aware of the `data.length == 0` edgecase which will throw a division by zero error. `double average = (data.length > 0) ? (double) sum / data.length : 0.0;` – James McGuigan Feb 15 '21 at 16:02
  • It's also worth noting that `(double) sum / data.length` without brackets also works in practice. Casting takes precedence over mathematical operators, thus `((double) sum)` becomes implicit, then the division operator propagates the double type. Personally, I think it is more readable, as the end result is to safely cast the whole division operation. http://bmanolov.free.fr/javaoperators.php – James McGuigan Feb 15 '21 at 16:07
  • It won't throw any errors, the result of `0.0 / 0.0` is `NaN`, which is the best way to answer the question "what is the average of an empty list". – Marko Topolnik Feb 15 '21 at 21:18
9

The Java 8 streaming api offers an elegant alternative:

public static void main(String[] args) {
    double avg = Arrays.stream(new int[]{1,3,2,5,8}).average().getAsDouble();

    System.out.println("avg: " + avg);
}
skubski
  • 1,586
  • 2
  • 19
  • 25
  • This really should be written as: `(int) Arrays.stream(new int[]{}).average().orElse(0.0);` to handle the `OptionalDouble.empty` return value for an empty array. `.average()` returns a double by default, but can be casted if desired. – James McGuigan Feb 15 '21 at 15:43
7
-while(int i=0; i < data.length; i++) 
+for(int i=0; i < data.length; i++) 
CyberDem0n
  • 14,545
  • 1
  • 34
  • 24
0

Try this way

public void average(int[] data) {  
    int sum = 0;
    double average;

    for(int i=0; i < data.length; i++){
        sum = sum + data[i];
    }
    average = (double)sum/data.length;
    System.out.println("Average value of array element is " + average);    
}

if you need to return average value you need to use double key word Instead of the void key word and need to return value return average.

public double average(int[] data) {  
    int sum = 0;
    double average;

    for(int i=0; i < data.length; i++){
        sum = sum + data[i];
    }
    average = (double)sum/data.length;
    return average;    
}
mssb
  • 878
  • 1
  • 8
  • 19
0

Best way to find the average of some numbers is trying Classes ......

public static void main(String[] args) {
    average(1,2,5,4);

}

public static void average(int...numbers){
    int total = 0;
    for(int x: numbers){
        total+=x;
    }
    System.out.println("Average is: "+(double)total/numbers.length);

}
0
  double[] numArray = { 45.3, 67.5, -45.6, 20.34, 33.0, 45.6 };
    double sum = 0.0;

    for (double num: numArray) {
       sum += num;
    }

    double average = sum / numArray.length;
    System.out.format("The average is: %.2f", average);
-2

Couple of problems:

The while should be a for You are not returning a value but you have declared a return type of double

double average = sum / data.length;;

sum and data.length are both ints so the division will return an int - check your types

double semi-colon, probably won't break it, just looks odd.

James
  • 2,483
  • 2
  • 24
  • 31
-2

If we want to add numbers of an Array and find the average of them follow this easy way! .....

public class Array {

    public static void main(String[] args) {

        int[]array = {1,3,5,7,9,6,3};
        int i=0;
        int sum=0;
        double average=0;
        for( i=0;i<array.length;i++){
            System.out.println(array[i]);
            sum=sum+array[i];
        }
        System.out.println("sum is:"+sum);
        System.out.println("average is: "+(double)sum/vargu.length);



    }

}
benka
  • 4,732
  • 35
  • 47
  • 58
  • Where does vargu come from? Why do you declare an variable average and not use it? Why do you declare the fori loop iteration variable outside the loop? – skubski Oct 05 '17 at 12:00