我有两节课。第一个是完整的,它正在制作一个 Item 对象:
public class Item {
private String name; // The Name of the item.
private int unitPrice; // The price of each unit of this item, in cents.
private int quantity; // The number of units of this item.
// CONSTRUCTOR
/*
* Constructs an item with specified name, price, and quantity.
*/
public Item(String name, int unitPrice, int quantity) {
this.name = name;
this.unitPrice = unitPrice;
this.quantity = quantity;
}
// METHODS
/*
* Gets the name for the item. Returns the name for this item.
*/
public String getName() {
return name;
}
/*
* Gets the price of each unit of a given item, in cents. Return the price.
*/
public int getUnitPrice() {
return unitPrice;
}
/*
* Gets and returns the number of units of this item.
*/
public int getQuantity() {
return quantity;
}
/*
* Increases or decreases the quantity of this item. If value is positive,
* quantity increases. If negative, quantity decreases.
*/
public void changeQuantity(int value) {
quantity = quantity + value;
}
/*
* Gets the total price, in cents. Returns the productof quantity and
* unitPrice as the total price of this item.
*/
public int getTotalPrice() {
return quantity * unitPrice;
}
/*
* Returns a string of this item, including name, price($)
*/
public String toString() {
return name + ": " + quantity + " ($" + unitPrice / 100 + "."
+ unitPrice % 100 + " per unit)";
}
}
现在,我正在尝试做一个 findItem 方法,我在其中搜索。不完全确定该怎么做。我想浏览所有库存并尝试匹配名称。我相信我应该使用 getName() 但不确定如何遍历每个名称。
public class Store {
private ArrayList<Item> inventory;
//MOTHODS
/*
* Finds an item by its name if it is part of the store's inventory
* Name is case-insensitive
* Returns the Item object corresponding to the given name if the item was found. If an item with the given name was not found, then this method returns null.
*/
public Item findItem(String name){
for(int i=0; i<inventory.size();i++){
if(name.toUpperCase().equals(?????))
}
}
}
谢谢您的帮助。