import javax.swing.*;
import java.util.Scanner;
class Goodsinfor{
private int num;
private String name;
private double price;
public Goodsinfor(int num,String name){
this.num=num;
this.name=name;
}
public int getNum(){
return num;
}
public void setNum(int num){
this.num=num;
}
public String getName(){
return name;
}
public void setName(String name){
this.name=name;
}
public double getPrice(){
int price=getNum();
switch (price){
case 001:price=8;
break;
case 002:price=6;
break;
case 003:price=4;
break;
case 004:price=5;
break;
default:price=2;
}
return price;
}
public void inforShow(){
System.out.println("Goods num="+getNum()+",name="+getName()+",price="+getPrice());
}
}
class Buy{
private double money=0;
public double sellMoney(Goodsinfor num,int nums){
double price=num.getPrice()*nums;
return money=money+price;
}
public double getMoney(){
return money;
}
}
public class bibproject1 {
public static void main(String[] args) {
System.out.println("#################");
System.out.println("欢迎来到**超市");
System.out.println("################");
String m1, m2;
int md1 = 0, md2 = 0;
do {
System.out.println("1.展示商品");
System.out.println("2.购买商品");
System.out.println("0.退出");
m1 = JOptionPane.showInputDialog(null, "请输入命令");
switch (m1) {
case "0":
System.exit(0);
break;
case "1":
md1 = 1;
break;
case "2":
md1 = 2;
break;
}
if (md1 == 1) {
Goodsinfor g1 = new Goodsinfor(001, "可口可乐");
Goodsinfor g2 = new Goodsinfor(002, "雪碧");
Goodsinfor g3 = new Goodsinfor(003, "冰红茶");
Goodsinfor g4 = new Goodsinfor(004, "牛奶");
Goodsinfor g5 = new Goodsinfor(005, "零食");
g1.inforShow();
g2.inforShow();
g3.inforShow();
g4.inforShow();
g5.inforShow();
}
if (md2 == 2) {
Buy buy = new Buy();
System.out.println("请输入编号,名称,数量");
Scanner in = new Scanner(System.in);
int num = in.nextInt();
String name = in.nextLine();
int nums = in.nextInt();
Goodsinfor g1 = new Goodsinfor(num, name);
buy.sellMoney(g1, nums);
double counmoney = buy.getMoney();
System.out.println("总价是:" + counmoney);
}
m2=JOptionPane.showInputDialog(null,"输入y继续,n退出");
switch (m2){
case "y":
md2=1;
break;
case "n":
md2=-1;
break;
}
}while (md2>0);
System.exit(0);
}
}
运行结果:
解题思路:1.想好需要实现的功能,分别构造相应的类和方法。2.将带main方法的类构造出来,然后调用其他的类实现需要的功能,完成主类的构造。
注意:各种类的构造要分文件,分包,这样更好,有利于后面代码的修改,也符合项目构建的要求,我没改,是为了方便展示,请见谅。
希望对大家有帮助,谢谢观看。