Arraylist案例

Arraylist是使用最频繁的一个集合,它与数组类似,不同之处在于它可以动态改变长度,不够了可以扩容。

案例:

Arraylist案例_第1张图片

我的思考:

首先多个菜品信息可以用Arraylist 来存储,那我们需要再创建一个菜品类Food,为了实现菜品上架等等功能,再创建一个FoodOperator类进行操作。

我的代码:

//Food.java

public class Food {
    private String name;
    private double price;
    private int score;

    public Food() {
    }


    public Food(String name, double price, int score) {
        this.name = name;
        this.price = price;
        this.score = score;
    }

    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 double getScore() {
        return score;
    }

    public void setScore(int score) {
        this.score = score;
    }
}
// FoodOperator.java

public class FoodOperator {
    ArrayList list = new ArrayList<>();

    public void addFood(){
        Food food = new Food();
        Scanner sc = new Scanner(System.in);
        System.out.println("请你输入菜品名字");
        String name = sc.next();
        food.setName(name);
        System.out.println("请你输入菜品价格");
        double price = sc.nextDouble();
        food.setPrice(price);
        System.out.println("请你输入菜品评级");
        int score = sc.nextInt();
        food.setScore(score);

        list.add(food);
    }

    public void print(){
        System.out.println("-----------------");
        System.out.println("菜品信息");
        for (int i = 0; i < list.size(); i++) {
            Food f = list.get(i);
            System.out.println(f.getName());
            System.out.println(f.getPrice());
            System.out.println(f.getScore());
            System.out.println("-----------------");
        }
    }

    public void start(){
        Scanner sc = new Scanner(System.in);
        System.out.println("操作1:上架菜品");
        System.out.println("操作2:打印菜品");
        System.out.println("操作0:退出");
        while (true){
            System.out.println("请输入你要选择的操作");
            String commend = sc.next();
            switch(commend){
                case "0":
                    return;
                case "1":
                    addFood();
                    break;
                case "2":
                    print();
                    break;
                default:
                    System.out.println("输入无效指令,请重试");
                    break;
            }
        }
    }
}
// Test.java

public class Test {
    public static void main(String[] args) {
        FoodOperator foodOperator = new FoodOperator();
        foodOperator.start();
    }
}

Arraylist案例_第2张图片

你可能感兴趣的:(java,算法,开发语言)