ArrayList集合做DVD租赁项目
时间: 2023-09-02 07:07:16 浏览: 139
好的,下面是使用ArrayList集合实现DVD租赁项目的简单示例代码:
```
import java.util.ArrayList;
import java.util.Scanner;
public class DVDStore {
private ArrayList<DVD> dvdList = new ArrayList<DVD>();
private ArrayList<DVD> rentedList = new ArrayList<DVD>();
private Scanner scanner = new Scanner(System.in);
public void addDVD() {
System.out.println("请输入DVD名称:");
String name = scanner.nextLine();
System.out.println("请输入DVD分类:");
String category = scanner.nextLine();
DVD dvd = new DVD(name, category);
dvdList.add(dvd);
System.out.println("DVD添加成功!");
}
public void removeDVD() {
System.out.println("请输入要删除的DVD名称:");
String name = scanner.nextLine();
DVD dvd = findDVD(name, dvdList);
if (dvd != null) {
dvdList.remove(dvd);
System.out.println("DVD删除成功!");
} else {
System.out.println("未找到该DVD!");
}
}
public void rentDVD() {
System.out.println("请输入要租借的DVD名称:");
String name = scanner.nextLine();
DVD dvd = findDVD(name, dvdList);
if (dvd != null) {
dvdList.remove(dvd);
rentedList.add(dvd);
System.out.println("DVD租借成功!");
} else {
System.out.println("未找到该DVD!");
}
}
public void returnDVD() {
System.out.println("请输入要归还的DVD名称:");
String name = scanner.nextLine();
DVD dvd = findDVD(name, rentedList);
if (dvd != null) {
rentedList.remove(dvd);
dvdList.add(dvd);
System.out.println("DVD归还成功!");
} else {
System.out.println("未找到该DVD!");
}
}
public void listDVDs() {
System.out.println("DVD列表:");
for (DVD dvd : dvdList) {
System.out.println(dvd.getName() + " - " + dvd.getCategory());
}
System.out.println("已租借的DVD列表:");
for (DVD dvd : rentedList) {
System.out.println(dvd.getName() + " - " + dvd.getCategory());
}
}
private DVD findDVD(String name, ArrayList<DVD> dvdList) {
for (DVD dvd : dvdList) {
if (dvd.getName().equals(name)) {
return dvd;
}
}
return null;
}
public static void main(String[] args) {
DVDStore store = new DVDStore();
boolean loop = true;
while (loop) {
System.out.println("DVD租赁系统");
System.out.println("1. 添加DVD");
System.out.println("2. 删除DVD");
System.out.println("3. 租借DVD");
System.out.println("4. 归还DVD");
System.out.println("5. 显示DVD列表");
System.out.println("6. 退出系统");
System.out.println("请选择操作:");
String choice = store.scanner.nextLine();
switch (choice) {
case "1":
store.addDVD();
break;
case "2":
store.removeDVD();
break;
case "3":
store.rentDVD();
break;
case "4":
store.returnDVD();
break;
case "5":
store.listDVDs();
break;
case "6":
loop = false;
break;
default:
System.out.println("无效的选择!");
}
}
System.out.println("系统已退出!");
}
}
class DVD {
private String name;
private String category;
public DVD(String name, String category) {
this.name = name;
this.category = category;
}
public String getName() {
return name;
}
public String getCategory() {
return category;
}
}
```
这个示例代码实现了DVD租赁系统的基本功能,包括添加、删除、租借、归还和显示DVD列表等操作。其中,DVD类用于封装DVD的名称和分类信息,DVDStore类用于维护DVD列表和租借列表,并提供各种操作方法,main方法用于提供用户交互界面。在实现过程中,我们使用了ArrayList集合来存储DVD对象,并通过遍历集合来查找和操作DVD对象。
阅读全文