1、需求说明
2、代码
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Scanner;
/**
* 购物车系统
* @author com
*
*/
public class ListShopping {
static Scanner sc = new Scanner(System.in);
static ArrayList list = new ArrayList<>();
public static void main(String[] args) {
manu();
}
public static void manu() {
System.out.println("**********************菜单***********************");
System.out.println(" 1.添加 2.修改数量 3.删除商品 4、查询全部 5.退出");
System.out.println("*************************************************");
while(true) {
System.out.print("* 输入选择:");
int in = sc.nextInt();
if(in == 1) add();
if(in == 2) updata();
if(in == 3) delete();
if(in == 4) query();
if(in == 5) exit();
}
}
/**
* 1.添加
*/
public static void add() {
System.out.print("* 输入编号:");
int id = sc.nextInt();
System.out.print("* 输入名称:");
String name = sc.next();
System.out.print("* 输入价格:");
Double price = sc.nextDouble();
System.out.print("* 输入数量:");
int amount = sc.nextInt();
Commodity com = new Commodity(id,name,price,amount);
list.add(com);
}
/**
* 2.修改
*/
public static void updata() {
System.out.print("* 输入要修改的编号:");
int id = sc.nextInt();
System.out.print("* 输入新的数量:");
int amount = sc.nextInt();
boolean bool = true;
for(int i=0;i it = list.iterator();
while(it.hasNext()) {
System.out.println(it.next());
}
// for(Commodity com:list) {
// System.out.println(com.getId()+"\t"+com.getName()+"\t"+com.getPrice()+"\t"+com.getAmount());
// }
System.out.println("查询成功:");
}
/**
* 5.退出
*/
public static void exit() {
System.out.print("* y(是) n(否) 确认退出:");
String in = sc.next();
if(in.equals("y")) {
System.exit(0);
}else if(in.equals("n")) {
return;
}else {
System.out.println("输入错误!!!");
}
}
}
/**
* 商品类
* @author com
*
*/
class Commodity {
private int id;
private String name;
private double price;
private int amount;
Commodity(int id,String name,double price,int amount){
this.id = id;
this.name = name;
this.price = price;
this.amount = amount;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public int getAmount() {
return amount;
}
public void setAmount(int amount) {
this.amount = amount;
}
@Override
public String toString() {
return id+"\t"+name+"\t"+price+"\t"+amount;
}
}
3、运行效果
4、总结
ArrayList可以实现增删改查,这是java初学面向对象过度到JavaEE的一个典型的练习例子。
添加:ArrayList.add()
删除:ArrayList.remove()
修改:ArrayList.get() 先用for循环加get方法找到数组下标的位置,再通过对象的setXxx方法修改。
查询:Iterator<类型> it = ArrayList.iterator(); 迭代器遍历,Iterator的hasNext()和nex()t方法遍历查询。