方法 getPosition 使用类 ArrayLinearList 中的方法 indexOf 返回列表中项目的位置,每当我传递 String 的参数时,即使该项目存在于列表中,它也始终返回 -1
private ArrayLinearList array;
private Scanner scanner;
public ArrayShoppingList1()
{
array = new ArrayLinearList();
scanner = new Scanner(System.in);
}
public int getPosition()
{
System.out.println("Please enter the name of the Item");
String name = scanner.nextLine();
int z = array.indexOf(name);
return z;
}
/** @return index of first occurrence of theElement,
* return -1 if theElement not in list */
public int indexOf(Object theElement)
{
// search element[] for theElement
for (int i = 0; i < size; i++)
if (element[i].equals(theElement))
return i;
// theElement not found
return -1;
}