⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 exercise 4.order.java

📁 CMU SSD3 课程完整答案(除EXAM)
💻 JAVA
字号:
import java.util.*;

/**
 * The class maintains a list of order items. This class implements the
 * interface Iterable<OrderItem> to being able to iterate through the items
 * using the for-each loop.
 * 
 * @author Neil
 * @version 1.1.0
 * @see OrderItem
 */
public class Order implements Iterable<OrderItem> {
	
	private ArrayList<OrderItem> items;

	/**
	 * Creates the collection items, which is initially empty.
	 */
	public Order() {
		
		items = new ArrayList<OrderItem>();		
	}

	/**
	 * Adds the specified order item to the collection items.
	 * 
	 * @param orderItem
	 *            the order item to be added.
	 */
	public void addItem(OrderItem orderItem) {
		
		items.add(orderItem);		
	}

	/**
	 * Removes the specified order item from the collection items.
	 * 
	 * @param orderItem
	 *            the order item to be removed.
	 */
	public void removeItem(OrderItem orderItem) {
		
		for (Iterator<OrderItem> i = items.iterator(); i.hasNext();) {
			if (i.next() == orderItem) {
				i.remove();
				return;
			}
		}
	}

	/**
	 * Returns an iterator over the instances in the collection items.
	 * 
	 * return an iterator over the instances in the collection items.
	 */
	public Iterator<OrderItem> iterator() {
		
		return items.iterator();
	}

	/**
	 * Returns a reference to the OrderItem instance with the specified product.
	 * Returns null if there are no items in the order with the specified
	 * product.
	 * 
	 * @param product
	 *            the specified product.
	 * @return Returns a reference to the OrderItem instance with the specified
	 *         product. Returns null if there are no items in the order with the
	 *         specified product.
	 */
	public OrderItem getItem(Product product) {
		
		for (Iterator<OrderItem> i = items.iterator(); i.hasNext();) {
			OrderItem item = i.next();
			if (item.getProduct().equals(product))
				return item;
		}
		return null;
	}

	/**
	 * Returns the number of instances in the collection items.
	 * 
	 * @return Returns the number of instances in the collection items.
	 */
	public int getNumberOfItems() {
		
		return items.size();
	}

	/**
	 * Returns the total cost of the order.
	 * 
	 * @return Returns the total cost of the order.
	 */
	public double getTotalCost() {
		
		double result = 0;
		
		for (Iterator<OrderItem> i = items.iterator(); i.hasNext();) {
			result += i.next().getValue();
		}
		return result;
	}
}

⌨️ 快捷键说明

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