我有两节课。第一个是完成的,它正在创建一个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(?????))
}
}
}
感谢您的帮助。
答案 0 :(得分:1)
为什么不使用for-each循环?
public Item findItem(String name)
{
for(Item item : inventory)
{
if(item.getName().equalsIgnoreCase(name))
{
return item;
}
}
return null;
}
答案 1 :(得分:0)
您的name
对象中已有Item
的getter,剩下的就是......
if(name.equalsIgnoreCase(use-your-getter-here()))
答案 2 :(得分:0)
public Item findItem(String name){
for(int i=0; i<inventory.size();i++){
if(name.toUpperCase().equals(inventory.get(i)))
}
答案 3 :(得分:0)
以下是您需要的代码:
import java.util.ArrayList;
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(inventory.get(i).getName().toUpperCase())) {
return inventory.get(i);
}
}
return null;
}
}