averagecalculator.java

来自「国外的数据结构与算法分析用书」· Java 代码 · 共 44 行

JAVA
44
字号
package simple;

/**	A list traverser that will process the list and compute the average of its values. */
public class AverageCalculator extends ListTraverser
{
	/**	Sum of the values. */
	protected double total;

	/**	Number of values. */
	protected int count;

	/**	Constructor that uses the default values for instance variables.
		Analysis: Time = O(1) */
	public AverageCalculator() {}

	/**	Average of the values.
		Analysis: Time = O(1)
		PRECONDITION:
			!(count <= 0) */
	public double average() throws Exception
	{
		if (count <= 0)
			throw new Exception("A nonempty list must be processed before the "
					+ "average can be obtained.");
		return total/count;
	}

	/**	Actions done to an item.
		Analysis: Time = O(1) */
	public void itemActions(Object item)
	{
		total = total + ((Number)item).doubleValue();
		count++;
	}

	/**	Actions to be performed before each traversal. 
		Analysis: Time = O(1) */
	public void beforeActions()
	{
		total = 0;
		count = 0;
	}
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?