1. 程式人生 > >java:練習超市賣場

java:練習超市賣場

emp boolean getcount pub return urn arp str !=

java:練習超市賣場

涉及到:大商品類,具體商品(以書為例),賣場類

Goods,Book,superMart,

商品類Goods:

public interface Goods {

	//商品類
	public String getName();
	public int getCount();
	public float getPrice();
	
	
	
	
}

 書:

註意:復寫hashCode,和equals是為了實現刪除按鈕

package abc;

public class Book implements Goods {

	private String name;
	private int count;
	private float price;
	public String getName() {
		return name;
	}
	
	
	
	
	public Book() {
		super();
	}




	public Book(String name, int count, float price) {
		super();
		this.name = name;
		this.count = count;
		this.price = price;
	}

	
	



	public void setName(String name) {
		this.name = name;
	}
	
	public int getCount() {
		return count;
	}
	
	public void setCount(int count) {
		this.count = count;
	}
	
	public float getPrice() {
		return price;
	}
	
	public void setPrice(float price) {
		this.price = price;
	}

	
	


	//復寫hashCode,和equals是為了實現刪除按鈕
	@Override
	public int hashCode() {
		return this.name.hashCode() + 
				new Integer(this.count).hashCode() +
				 new Float(this.price).hashCode();
	}



	//復寫hashCode,和equals是為了實現刪除按鈕
	@Override
	public boolean equals(Object obj) {
		if(obj == this)
		{
			return true;
		}
		if(!(obj instanceof Book))
		{
			return false;
		}
		Book b = (Book) obj;
		if( b.name.equals(this.name) && b.count == this.count && b.price == this.price)
		{
			return true;
		}else {
			return false;
		}
	}




	@Override
	public String toString() {
		return "書名:" + name + ", 數量:" + count + ", 價格:" + price ;
	}
	
	
	
	
	
	
	
	
	
}

  

超級市場:

需要註意remove刪除方法,必須在BOOK中定義相關的equals,hashCode方法才能刪除

//刪除,需要復寫book裏面的equals和hasCode
remove(Goods good)
package abc;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class SuperMark {

	private List<Goods> allGoods;


	public SuperMark()
	{
		this.allGoods = new ArrayList<Goods>();
	}
	
	
	public void add(Goods good)
	{
		this.allGoods.add(good);
	}
	
	//刪除,需要復寫book裏面的equals和hasCode
	public void remove(Goods good)
	{
		this.allGoods.remove(good);
	}
	
	public List<Goods> search(String keyword)
	{
		List<Goods> temp = new ArrayList<Goods>();
		Iterator<Goods> iter = this.allGoods.iterator();
		while(iter.hasNext())
		{
			Goods g = iter.next();
			if(g.getName().indexOf(keyword) != -1)
			{
				temp.add(g);
			}
		}
		return temp;
	}
	
	
	public List<Goods> getAllGoods()
	{
		return this.allGoods;
	}
	
	
	
}

  

測試:

public class Demo {

	public static void main(String[] args) {
		// TODO 自動生成的方法存根

		System.out.println("gaga");
		
		
		
		SuperMark sm = new SuperMark();
		sm.add(new Book("java",5,10.4f));
		sm.add(new Book("net",6,22.f));
		sm.add(new Book("php",6,10f));
		
		print(sm.search("j"));
		
		
		
	}
	
	
	public static void print(List all)
	{
		Iterator iter = all.iterator();
		while(iter.hasNext())
		{
			System.out.println(iter.next());
		}
	}

}

  

 

java:練習超市賣場