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);
}
}
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;
}
}
}
}
}
}