[英]Shopping Cart in Java
我正在做一項工作,我必須有一個帶有GUI的郵票商店,用戶需要能夠在購物卡中添加和刪除商品,然后在客戶結賬時將訂單收據打印到文件中。 我的購物車存在很多問題,因為我不確定是否正確添加了商品,因為我無法顯示它們。 目前,購物車的代碼是
ShoppingCart.java
import java.util.ArrayList;
import java.util.List;
public class ShoppingCart
{
static // creates arraylist for cart
List<CartItem> items = new ArrayList<CartItem>();
public void AddItem(CartItem store)
{
items.add(store);
}
public static void main(String[] args)
{
System.out.println(items.get(0));
}
}
Item.java
import java.util.ArrayList;
import java.util.List;
public class Item
{
ShoppingCart cart;
public void CartSelection()
{
CartItem items = new CartItem("Parcel", 12, "Italy", true, 10.00);
cart.AddItem(items);
}
}
CartItem.java
import java.util.ArrayList;
import java.util.List;
// creates a class to store items in cart arraylist
public class CartItem
{
public CartItem(
String Type,
Integer Weight,
String Destination,
Boolean NovDec,
Double Price)
{
}
}
首先,代碼給出了一個錯誤,說明The method get(int) is undefined for the type CartItem
。
在找到問題的原因之后,我現在改變了代碼
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
at java.util.ArrayList.rangeCheck(ArrayList.java:638)
at java.util.ArrayList.get(ArrayList.java:414)
at ShoppingCart.main(ShoppingCart.java:16)
任何有關正確方向的幫助或指示都將不勝感激。
看起來你的main方法調用System.out.println(items.get(0));
在任何項目添加到列表之前。 這解釋了java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
。
在訪問列表之前,您必須檢查索引是否有效:
public static void main(String[] args)
{
if (items.size() > 0)
System.out.println(items.get(0));
}
這樣可以防止異常,但我不確定它會給你帶來多少接近你想要實現的東西。
這是輸入兩個項目然后打印它的好方法。
public class ItemToPurchase
{
public String itemName;
public int itemPrice;
public int itemQuantity;
public ItemToPurchase()
{
itemName="none";
itemPrice=0;
itemQuantity=0;
}
public void setName(String name)
{
itemName = name;
}
public String getName()
{
return itemName;
}
}
繼續其他變量/數據成員
然后是主要方法
import java.util.Scanner;
public class ShoppingCartPrinter
{
public static void main(String[] args)
{
ItemToPurchase item1= new ItemToPurchase();
ItemToPurchase item2= new ItemToPurchase();
Scanner kbdInput = new Scanner(System.in);
System.out.println("Item 1");
System.out.println( "Enter the item name: ");
item1.setName(kbdInput.nextLine());
etc...
kbdInput.nextLine();
...
System.out.println ( "Enter the item quantity: ");
item2.setQuantity(kbdInput.nextInt());
int totalItem1 = item1.getPrice()* item1.getQuantity();
System.out.println ("\n"+"TOTAL COST");
System.out.println (item1.getName()+" "+item1.getQuantity()+" "+" @ $" +totalItem1);
etc...
System.out.println ("Total: $"+ (totalItem1 + totalItem2));
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.