英文:
Pass Multiple Parameters into an Array List (Java)
问题
我正在尝试设置一个数组列表,用于存储购物清单上的项目。我希望该列表能够存储每个项目的名称、价格和税收信息。是否可以设置一个ArrayList来同时接受字符串和整数参数?我已经在下面包含了我的代码:
public class ItemList
{
// 实例变量 - 用你自己的内容替换下面的示例
private ArrayList<String> items;
private String itemName;
private int cost;
private String taxable;
/**
* ItemList类的构造函数
*/
public ItemList()
{
items = new ArrayList<>();
}
/**
* 向ItemList中添加一个项目
*/
public void addItem(String itemName, int cost, String taxable)
{
items.add(itemName, cost, taxable);
}
}
英文:
I am trying to set up an array list that will store items on a grocery list. I would like the for the list to store the name, price, and tax information for each item. Is it possible to set up an ArrayList so that it accepts both String and integer parameters? I've included my code below:
public class ItemList
{
// instance variables - replace the example below with your own
private ArrayList<String> items;
private String itemName;
private int cost;
private String taxable;
/**
* Constructor for objects of class ItemList
*/
public ItemList()
{
items=new ArrayList<>();
}
/**
* Adds an item to the ItemList
*/
public void addItem(String itemName, int cost, String taxable)
{
items.add(itemName, cost, taxable);
}
}
答案1
得分: 2
以下是翻译好的内容:
正确的方法是创建一个Item
类,并拥有一个这些类的List
。Item
类应该有一个接受必要变量的构造函数。
然后你可以这样做:
private ArrayList<Item> items;
// ...
public void addItem(String itemName, int cost, String taxable)
{
items.add(new Item(itemName, cost, taxable));
}
英文:
The correct way would be to create a Item
class and have a List
of these. The Item would have a constructor that takes the necessary variables.
Then you could do
private ArrayList<Item> items;
.....
public void addItem(String itemName, int cost, String taxable)
{
items.add(new Item(itemName, cost, taxable));
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论