首页 > 解决方案 > 如何从 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()方法打印已从列表中删除的食物总量(公斤)。

标签: javaarraylistmethodstostring

解决方案


只需添加一个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!

推荐阅读