我有一个名为ItemToPurchase的类,它具有私有变量声明和公共方法来设置和获取这些变量的值。这个类还有一个defualt construtor和一个constinctor,它将String的itemName和itemDescription作为参数。 例如:
public class ItemToPurchase{
private String itemName;
public void setName(String name){
...
}
public String getName(){
return name;
}
}
然后是另一个名为购物车的类,它做同样的事情,它也包含这个方法。
private ArrayList<ItemToPurchase> cartItems;
cartItems = new ArrayList<ItemToPurchase>();
public void removeItem(String itemName) {
if (cartItems.contains(itemName)) {
cartItems.remove(itemName);
} else {
System.out.println("Item not found in cart. Nothing removed.");
}
}
并且类ShoppingCartManager包含main,并且主要有一个循环,它打印一个看起来像这样的菜单。
ShoppingCart cart = new ShoppingCart(cName, tDate);
public static void main(String[] args) {
sc = new Scanner(System.in);
ShoppingCart object = new ShoppingCart();
System.out.println("Enter Customer's Name: ");
String cName = sc.nextLine();
System.out.println("Enter Today's Date: ");
String tDate = sc.nextLine();
System.out.println("Customer Name: " + cName + "\n" + "Today's Date: "
+ tDate);
ShoppingCart cart = new ShoppingCart(cName, tDate);
printMenu(cart);
}
public static void printMenu(ShoppingCart cart) {
char input;
do {
System.out.println("Menu");
System.out.println("a - Add item to cart");
System.out.println("d - Remove item from cart");
System.out.println("q - Quit");
System.out.println("");
System.out.print("Choose an option: ");
input = sc.next().charAt(0);
switch (input) {
case 'a':
addItem(cart);
break;
case 'd':
removeItem(cart);
break;
default:
}
} while (input != 'q');
}
public static void removeItem(ShoppingCart cart) {
System.out.println("REMOVE ITEM FROM CART");
System.out.println("");
System.out.print("Enter name of item to remove: ");
String itemName = sc.next().trim();
ShoppingCart object = new ShoppingCart();
object.removeItem(itemName);
}
public static void changeItem(ShoppingCart cart) {
System.out.println("CHANGE ITEM QUANTITY");
System.out.print("Enter the item name: ");
System.out.println("");
String itemName = sc.next().trim();
System.out.println("Enter the new quantity: ");
int nQuantity = sc.nextInt();
ItemToPurchase oItemName = new ItemToPurchase();
if (itemName.equals(oItemName.getName())){
oItemName.setQuantity(nQuantity);
}
任何人都可以解释为什么removeItem()和changeItem()方法不起作用? 如果您需要了解有关代码的更多信息,请与我们联系。
答案 0 :(得分:0)
public static void removeItem(ShoppingCart cart) {
System.out.println("REMOVE ITEM FROM CART");
System.out.println("");
System.out.print("Enter name of item to remove: ");
String itemName = sc.next().trim();
ShoppingCart object = new ShoppingCart();
object.removeItem(itemName);
}
您没有使用的参数购物车, changeItem(ShoppingCart购物车)方法也是如此。请检查一下。
答案 1 :(得分:0)
您的removeItem
方法在String
列表中查找ItemToPurchase
。 contains方法调用String上的equals
和cartItems中寻找匹配项的每个对象。当然它找不到它。
将您的方法更改为以下内容:
public void removeItem(String itemName) {
for (int i = 0; i < cartItems.size(); i++) {
if (cartItems.get(i).equals(itemName)) {
cartItems.remove(i);
break;
}
}
}