java - 如何从 ArrayList 中删除索引并打印已删除索引的总整数?
问题描述
我想为仓库制作一个程序。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()
方法打印已从列表中删除的食物总量(公斤)。
解决方案
只需添加一个Food
存储移除总量的类成员(在类中)。在方法emptyStock()
中,您更新此成员的值。在下面的代码中,我添加了 member 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!
推荐阅读
- excel - 在输入列时复制值并粘贴到另一个工作表 - 我哪里出错了?
- linux - 如何测试文件是否可以标记为可执行并运行?
- apache-kafka - 使用 Logstash 将数据推送到 kafka 服务器
- javascript - 以编程方式在 HTMLElement 上设置“for”属性
- silverstripe - 使用过滤器方法对一对多关系数据进行 SilverStripe 过滤器不起作用
- java - 在类路径 Java 中找不到任何 META-INF/persistence.xml 文件 - 动态 Web 项目
- json - 如何将 49.000 个字符长的 json 字符串处理成 pl/sql 中的 clob
- r - 过滤 POSIXct 时间戳
- r - 基于条件的相邻列的总和
- python - 获取有关目录中文件的信息并在表格中打印