oop 商品信息按商品名稱查詢 商品按價格排序 內含測試類

class Product
public class Product{
	private int pid;//商品編號
	private String pname;//商品名稱
	private double price;//商品價格
	private int pnum;//商品數量
	
	public Product(){

	}
	public Product(int pid,String pname,double price,int pnum){
		this.pid=pid;
		this.pname=pname;
		this.price=price;
		this.pnum=pnum;
	}
	public double getPrice(){
		return this.price;
	}
	public String getPname(){
		return this.pname;
	}
	public void showInfo(){
		System.out.println("商品編號"+this.pid+"商品名稱"+this.pname+"商品價格"+this.price+"商品數量"+this.pnum);

	} 
}


      class      Test
import java.util.Random;
import java.util.Scanner;
public class Test {
	public static void main(String [] args){
		//存儲商品信息 聲明一個存儲商品信息的數據
		Product [] products=new Product[5];
		Random rd=new Random();
		//從鍵盤上輸入
		Scanner sc=new Scanner (System.in);
		for(int i=0;i<products.length;i++){
			System.out.println("請輸入商品編號");
			int pid=sc.nextInt();
			sc.nextLine();
			System.out.println("請輸入商品名稱");
			String pname=sc.nextLine();
			System.out.println("請輸入商品單價");
			double price=sc.nextDouble();
			System.out.println("請輸入商品數量");
			int pnum=sc.nextInt();
			//使用數組下標訪問每個商品信息
			products[i]=new Product(pid,pname,price,pnum);
		}
		//打印商品信息
		print(products);
		sc.nextLine();
		System.out.println("請輸入你要查找的商品信息");
		String name=sc.nextLine();
		//調用查找的方法
		int index=findByName(products,name);
		if(index<0){
			System.out.println("查無此商品");
		}else{
			products[index].showInfo();//打印商品信息
		}
		System.out.println("請對商品進行排序(desc/asc):");
		String input=sc.nextLine();
		order(products,input);
		System.out.println("排序之後的結果:");
		print(products);
	}
	//顯示所有商品信息
	public static void print(Product [] products){
		if(null==products){
			System.out.println("數組不能爲空");
			return ;
		}for(Product p:products){
			p.showInfo();//顯示信息
		}
		
	}


	//根據商品名稱查找商品信息
	public static int findByName(Product []products,String name){
		if(null==products){
			System.out.println("數組爲空");
			return -1;
		}
		//去除字符串的空格
		for(int i=0;i<products.length;i++){
			if(name.trim().equals(products[i].getPname().trim())){
				return i;
			}
		}
		return -1;
	}
	//排序
	public static void order(Product [] products,String str){
		if(null==products){
			System.out.println("數組爲空");
			return ;
		}
		//降序
		if("desc".equals(str)){
			for(int i=0;i<products.length-1;i++){
				for(int j=0;j<products.length-i-1;j++){
					Product temp=new Product();
					if(products[j].getPrice()<products[j+1].getPrice()){
						temp=products[j];
						products[j]=products[j+1];
						products[j+1]=temp;
					}
				}
			}
		}
		//升序
		if("asc".equals(str)){
			for(int i=0;i<products.length-1;i++){
				for(int j=0;j<products.length-i-1;j++){
					Product temp=new Product();
					if(products[j].getPrice()>products[j+1].getPrice()){
						temp=products[j];
						products[j]=products[j+1];
						products[j+1]=temp;
					}
				}
			}
		}
	}
	
} 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章