KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > gnu > xquery > util > Average


1 // Copyright (c) 2002 Per M.A. Bothner.
2
// This is free software; for terms and warranty disclaimer see ./COPYING.
3

4 package gnu.xquery.util;
5 import gnu.mapping.*;
6 import gnu.lists.*;
7 import gnu.math.*;
8 import gnu.kawa.functions.AddOp;
9
10 public class Average extends Procedure1
11 {
12   public static final Average avg = new Average("avg");
13
14   public Average (String JavaDoc name)
15   {
16     super(name);
17   }
18
19   public Object JavaDoc apply1(Object JavaDoc arg)
20     throws Throwable JavaDoc
21   {
22     Object JavaDoc sum = Values.empty;
23     int count = 0;
24     if (arg instanceof Values)
25       {
26     TreeList tlist = (TreeList) arg;
27     int index = 0;
28     for (;;)
29       {
30         Object JavaDoc next = tlist.getPosNext(index);
31         if (next == Sequence.eofValue)
32           break;
33         count++;
34             sum = sum == Values.empty ? next : ArithOp.add.apply2(sum, next);
35         index = tlist.nextPos(index);
36       }
37       }
38     else
39       {
40     count = 1;
41     sum = arg;
42       }
43     if (sum == Values.empty)
44       return sum;
45     return sum = ArithOp.div.apply2(sum, IntNum.make(count));
46   }
47 }
48
Popular Tags