package 水果管理系统;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
//定义一个水果类,定义一个水果名以及水果价格属性
class Fruit {
private String name;
private double price;
//定义一个全参构造器来实现水果信息初始化
public Fruit(String name, double price) {
this.name = name;
this.price = price;
}
public String getName() {
return name;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
@Override
public String toString() {
return "ccc.水果管理系统.Fruit [name=" + name + ", price=" + price + "]";
}
}
public class AYL {
//定义一个集合来保存水果信息
private List<Fruit> fruits;
//通过构造器来实现集合初始化
public void AYL() {
fruits = new ArrayList<>();
}
//添加水果信息。将传入的水果信息添加,通过集合的add方法添加到集合中
public void addFruit(Fruit fruit) {
fruits.add(fruit);
System.out.println("水果已成功添加!");
}
//删除水果信息。通过要删除的具体水果的索引,然后判断水果索引是否在区间内,是的话通过集合的remove方法删除
//由于集合是自动索引向前移动的,所以不需要像数组一样手动移动
public void removeFruit(int index) {
if (index >= 0 && index < fruits.size()) {
fruits.remove(index);
System.out.println("水果已成功删除!");
} else {
System.out.println("无效的索引!");
}
}
//修改水果信息。通过要修改的索引位置以及新的价格信息,判断索引是否在区间内,在的话修改对应的水果信息,通过set方法修改
public void modifyFruitPrice(int index, double newPrice) {
if (index >= 0 && index < fruits.size()) {
Fruit fruit = fruits.get(index);
fruit.setPrice(newPrice);
System.out.println("水果价格已成功修改!");
} else {
System.out.println("无效的索引!");
}
}
//查询水果信息。首先判断水果集合是否为空,如果为空的话,直接提示水果列表为空,如果不为空的话,通过for each循环来打印集合信息
public void displayAllFruits() {
if (fruits.isEmpty()) {
System.out.println("水果列表为空!");
} else {
for (Fruit fruit : fruits) {
System.out.println(fruit);
}
}
}
public static void main(String[] args) {
//初始化AYL类
AYL system = new AYL();
Scanner scanner = new Scanner(System.in);
int choice = 0;
//通过while循环实现主菜单循环
while (true) {
System.out.println("=====================");
System.out.println("1. 添加水果");
System.out.println("2. 删除水果");
System.out.println("3. 修改水果价格");
System.out.println("4. 查询所有水果");
System.out.println("5. 退出");
System.out.println("=====================");
System.out.print("请输入数字操作选项:");
choice = scanner.nextInt();
//通过chioce的输入信息来选择具体执行哪一个方法
switch (choice) {
case 1:
System.out.print("请输入水果名称:");
String name = scanner.next();
System.out.print("请输入水果价格:");
double price = scanner.nextDouble();
system.addFruit(new Fruit(name, price));
break;
case 2:
System.out.print("请输入要删除的水果索引:");
int removeIndex = scanner.nextInt();
system.removeFruit(removeIndex);
break;
case 3:
System.out.print("请输入要修改价格的水果索引:");
int modifyIndex = scanner.nextInt();
System.out.print("请输入新的价格:");
double newPrice = scanner.nextDouble();
system.modifyFruitPrice(modifyIndex, newPrice);
break;
case 4:
system.displayAllFruits();
break;
case 5:
System.out.println("退出程序!");
scanner.close();
System.exit(0);
default:
System.out.println("无效的选项!");
break;
}
}
}
}
水果管理系统
于 2023-12-30 09:57:02 首次发布