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



我想为仓库制作一个程序。emptyStock()方法应将已售出的食品从列表中删除。print()方法应打印所有已售出的食品清单和食品总量(kg(。

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()方法打印已从列表中删除的食物总量(kg(。

只需添加一个类成员(在类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!

最新更新