设计要求
设计超市商品管理系统,实现以下功能:
(1)输入5种商品名称、价格和数量;
(2)统计商品的总价格及平均价格,最高价和最低价;
(3)按价格降序排序;
(4)统计高于平均价格和低于平均价格的商品数量;
(5)输入商品名称查询商品的价格和数量。
实现代码
package work.chengxu;
import java.util.Scanner;
class Goods{
String[] name = new String[5];
double[] price = new double[5];
int[] number = new int[5];
double sum = 0;
double average = 0;
double max = 0;
double min = 0;
int lownum = 0;
int highnum = 0;
Scanner in =new Scanner(System.in);
public void Goods(){
for(int i=0; i<5; i++) {
int n = i+1;
System.out.print("请输入第"+n+"个商品的名称:");
Scanner a = new Scanner(System.in);
name[i] = a.nextLine();
System.out.print("请输入第"+n+"个商品的价格:");
Scanner b = new Scanner(System.in);
price[i] = b.nextDouble();
System.out.print("请输入第"+n+"个商品的数量:");
Scanner c = new Scanner(System.in);
number[i] = c.nextInt();
System.out.println();
}
}
public void show() {
for(int n=0; n<5; n++) {
int m = n+1;
System.out.println("第"+m+"个商品的名称为:"+name[n]);
System.out.println("第"+m+"个商品的价格为:"+price[n]);
System.out.println("第"+m+"个商品的数量为:"+number[n]);
System.out.println();
}
sum = price[0]+price[1]+price[2]+price[3]+price[4];
average = sum/5;
System.out.println("商品的总价为:"+sum);
System.out.println("商品的平均价为:"+average);
}
public void count(String name[],double price[],int number[]) {
for( int j=0; j<price.length; j++) {
double a = 0;
String b = null;
int c = 0;
for(int m=0; m<price.length-j-1; m++) {
if(price[m] < price[m+1]) {
a = price[m+1];
b = name[m+1];
c = number[m+1];
price[m+1] = price[m];
name[m+1] = name[m];
number[m+1] = number[m];
price[m] = a;
name[m] = b;
number[m] = c;
}
}
}
max = price[0];
min = price[price.length-1];
System.out.println("商品价格由低到高排序:");
System.out.print(price[4]+" ");
System.out.print(price[3]+" ");
System.out.print(price[2]+" ");
System.out.print(price[1]+" ");
System.out.print(price[0]+" ");
System.out.println();
System.out.println("商品的最高价:"+max+"\t商品的最低价"+min);
System.out.println();
for( int n=0; n<price.length; n++) {
if(price[n]<=average)
lownum++;
else
highnum++;
}
System.out.println("低于平均价的商品有"+lownum+"个");
System.out.println("高于平均价的商品有"+highnum+"个");
}
public void select(String name[],double price[],int number[]) {
System.out.println("请输入你想查询的商品名称");
String s = in.nextLine();
if(s.equals(name[0])) {
System.out.println("该商品价格为:"+price[0]);
System.out.println("该商品数量为:"+number[0]);
}else if(s.equals(name[1])) {
System.out.println("该商品价格为:"+price[1]);
System.out.println("该商品数量为:"+number[1]);
}else if(s.equals(name[2])) {
System.out.println("该商品价格为:"+price[2]);
System.out.println("该商品数量为:"+number[2]);
}else if(s.equals(name[3])) {
System.out.println("该商品价格为:"+price[3]);
System.out.println("该商品数量为:"+number[3]);
}else if(s.equals(name[4])) {
System.out.println("该商品价格为:"+price[4]);
System.out.println("该商品数量为:"+number[4]);
}else {
System.out.println("无此商品");
}
}
}
public class Test{
public static void main(String[] args) {
Goods g = new Goods();
g.Goods();
g.show();
g.count(g.name,g.price,g.number);
g.select(g.name,g.price,g.number);
}
}
运行结果
后面大家就可以自行输入相应查询的商品名称等,实现此系统的功能