本案例要求编写一个程序,模拟库存管理系统,该系统内容主要包括,商品入库,商品显示,和删除商品功能。(此程序用手机举例)
此管理系统分别为两个类Phone,和Test类
Phone类
确定四个变量(类)
1.生成空参数构造方法
2.全部参数的构造方法
3.生成全部参数的Setter和Getter方法
4.生成全部参数的to String方法
package anli06_1;
public class Phone {
private String name;
private String color;
private int price;
private int num ;
public Phone() {
}
public Phone(String name, String color, int price, int num) {
this.name = name;
this.color = color;
this.price = price;
this.num = num;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
public int getNum() {
return num;
}
public void setNum(int num) {
this.num = num;
}
@Override
public String toString() {
return "Phone{" +
"name='" + name + '\'' +
", color='" + color + '\'' +
", price=" + price +
", num=" + num +
'}';
}
}
Test类(测试类)
package anli06_1;
import java.util.ArrayList;
import java.util.Scanner;
public class Test {
static ArrayList<Phone> list =new ArrayList<>();
static Scanner sc =new Scanner(System.in);//键盘输入数据,,放在最前面每个方法均可使用
public static void main(String[] args) {
list.add(new Phone("小米手机","黑色",1999,20));
list.add(new Phone("华为手机","黑色",2999,30));
System.out.println("欢迎来到商品库存管理系统,请输入你的选择");
while(true){
System.out.println("1.商品入库");
System.out.println("2.商品显示");
System.out.println("3.删除商品");
System.out.println("4.退出系统");
int choice =sc.nextInt();
if (choice==1){
//商品入库
add();
show();
}else if (choice==2){
//商品显示
show();
}else if (choice==3){
//删除商品
delete();
show();
}else if (choice==4){
//退出系统
break;
}else {
System.out.println("您的输入有误");
}
}
}
private static void delete() {
System.out.println("请输入要输出第几个商品");
int i =sc.nextInt();//i当成索引,因为编号索引从0开始所以姚减去1
list.remove(i-1);
System.out.println("删除成功");
}
private static void show() {
if (list.size()==0){
System.out.println("目前暂时没有商品可以查看");
}else {
System.out.println("目前现有商品为");
for (Phone phone:list){
System.out.println(phone);
}
}
}
//商品入库方法
private static void add() {
System.out.println("确认要录入数据吗");
String choice = sc.next();
if ("yes".equals(choice)){
System.out.println("请输入商品名称");
String name=sc.next();
System.out.println("请输入商品颜色");
String color=sc.next();
System.out.println("请输入商品价格");
int price=sc.nextInt();
System.out.println("请输入商品数量");
int num=sc.nextInt();
Phone p =new Phone(name,color,price,num);
list.add(p);
System.out.println("添加成功");
}else{
return;//结束当前方法
}
}
}
结果展示