如何从 ArrayList 中删除索引并打印已删除索引的总整数?

How to remove index from ArrayList and print total integer of the removed index?

我想做一个仓库的程序。 emptyStock() 方法应该从列表中删除已售出的食物。 print() 方法应该打印所有食品清单和已售出的总食品(公斤)。

public class Lists {
private String name;
private String category;
private int amount;

public Lists(String name, String category, int amount) {
   this.name = name;
   this.category = category;
   this.amount = amount;
}

public String toString() {
    return name + " is " + category + " and we have " + amount + " in warehouse";
}
}

public class Food {
ArrayList<Lists> Food = new ArrayList<>();

public void add(String name, String category, int amount) {
    Food.add(new Lists(name, category, amount));
}

public void emptyStock(int index) {
    Food.remove(index);
}

public void print() {
    for (Lists lists : Food) {
        System.out.println(lists);
    }
}

public static void main(String[] args) {
    Food food = new Food();
    food.add("Potato", "Vegetable", 35);
    food.add("Carrot", "Vegetable", 15);
    food.add("Apple", "Fruit", 30);
    food.add("Kiwi", "Fruit", 5);
    food.emptyStock(1);
    food.emptyStock(2);
    food.print();
    System.out.print("");
}
}

输出需要这样打印:

Potato is Vegetable and we have 35 kg in warehouse
Apple is Fruit and we have 30 kg in warehouse
20 kg of food has been sold! // my code cannot print this part

我仍然不确定如何使print()方法打印出已从列表中删除的食物总量(千克)。

只需添加一个 class 成员(在 class Food 中)来存储移除的总金额。在方法 emptyStock() 中,您更新了该成员的值。在下面的代码中,我添加了成员​​ removed.

import java.util.ArrayList;

public class Food {
    int removed;
    ArrayList<Lists> foods = new ArrayList<>();

    public void add(String name, String category, int amount) {
        foods.add(new Lists(name, category, amount));
    }

    public void emptyStock(int index) {
        removed += foods.get(index).getAmount();
        foods.remove(index);
    }

    public void print() {
        for (Lists lists : foods) {
            System.out.println(lists);
        }
        System.out.printf("%d kg of food has been sold!%n", removed);
    }

    public static void main(String[] args) {
        Food food = new Food();
        food.add("Potato", "Vegetable", 35);
        food.add("Carrot", "Vegetable", 15);
        food.add("Apple", "Fruit", 30);
        food.add("Kiwi", "Fruit", 5);
        food.emptyStock(1);
        food.emptyStock(2);
        food.print();
        System.out.print("");
    }
}

class Lists {
    private String name;
    private String category;
    private int amount;

    public Lists(String name, String category, int amount) {
       this.name = name;
       this.category = category;
       this.amount = amount;
    }

    public int getAmount() {
        return amount;
    }

    public String toString() {
        return name + " is " + category + " and we have " + amount + " in warehouse";
    }
}

当运行以上代码为:

时的输出
Potato is Vegetable and we have 35 in warehouse
Apple is Fruit and we have 30 in warehouse
20 kg of food has been sold!