这是一个允许用户向系统添加数据的程序。这具体是程序的库存类,我们的任务是将对象库存转换为数组列表的对象...我是数组列表的新手,我需要一些帮助来解决这个问题。
我已经尝试了几次,但到目前为止还没有运气,任何帮助!
public class Inventory {
/**
* List of FoodItems that represents our inventory
*/
private FoodItem[] inventory;
/**
* Number of items that a user has entered
*/
private int numItems;
/**
* Default Constructor
*/
public Inventory() {
inventory = new FoodItem[20];
}
/**
* Reads from the Scanner object passed in and fills the data member fields of the class with valid data.
* @param scanner - Scanner to use for input
* @return <code>true</code> if all data members were successfully populated, <code>false</code> otherwise
*/
public boolean addItem(Scanner scanner) {
if(numItems == 20)
{
System.out.println("Inventory full");
return false;
}
boolean valid = false;
FoodItem item = null;
while(!valid)
{
System.out.print("Do you wish to add a fruit(f), vegetable(v) or a preserve(p)? ");
if(scanner.hasNext(Pattern.compile("[fFvVpP]")))
{
String choice = scanner.next();
switch(choice.toLowerCase())
{
case "f":
item = new Fruit();
break;
case "v":
item = new Vegetable();
break;
case "p":
item = new Preserve();
break;
default: // Should not get here.
item = new FoodItem();
break;
}
valid = true;
}
else
{
System.out.println("Invalid entry");
scanner.next();
valid = false;
}
}
慕丝7291255
相关分类