在线购物商店代码存在一些错误

时间:2019-03-28 05:16:28

标签: java

所以我一直在研究在线购物商店程序,它具有产品,帐户,订购的商品,购物车类以及包含产品和帐户的数组列表的商店类,我已经阅读了一些从文件中获取有关产品和帐户的信息,并将其存储在产品和帐户对象中,

(这是文件的一部分,向您展示它的外观) 0001,Nikon D3300带AF-P DX 18-55mm VR数码单反,Nikon,396.95,

0002,佳能EOS Rebel T6数码单反相机套件和EF-S 18-55mm f / 3.5-5.6 IS II镜头,佳能,400.95,

我想将这些对象添加到我前面提到的数组列表中,但这给了我这个错误:

线程“主”中的异常java.lang.NullPointerException     在programming2projectmain.Store.setArrProd(Programming2ProjectMain.java:462)     在programming2projectmain.Programming2ProjectMain.main(Programming2ProjectMain.java:69)

第69行: store.setArrProd(productObject);

和商店类:

public void setArrProd(Products x){

 (this is line 462)  arrprod.add(x);
    System.out.println(arrprod);
}

对于mu程序的第二个问题是,当我阅读产品信息(在for循环中)时,我也阅读了价格,因此我尝试打印它们,以便可以看到已存储的内容和未存储的内容。在循环中,它会按预期打印所有价格,但是一旦我知道了,它只会打印最后一个..这对我来说是个问题,因为我需要每种产品的价格来计算购物车中产品的总数,但我也不会不知道如何获取已添加商品的特定价格...

这是我的商店类别:

class Store{
private String name;
private ArrayList<Account> arracc;
private ArrayList<Products> arrprod;
public Store(){

}
public Store(String name){
    this.name=name;
}
public ArrayList<Account> getArracc() {
    return arracc;
}

public ArrayList<Products> getArrprod() {
    return arrprod;
}

public int getAccountSize(){
    return arracc.size();
}
public void setArrAcc(Account x){
    arracc.add(x);
}
public void setArrProd(Products x){
   arrprod.add(x);
    System.out.println(arrprod);
}

public void addProduct(Products p){
    arrprod.add(p);
}
public void deleteProduct(int id){
    arrprod.remove(id);//id is the product index

}
public void setName(String name){
    this.name=name;
}
public String getName(){
    return name;
}

}

购物车类别:

  class ShoppingCart{
  ArrayList<OrderedItem> orderedItems=new ArrayList<OrderedItem>();
  OrderedItem orders=new OrderedItem();

  public ShoppingCart(OrderedItem x) {
    orderedItems.add(x);
  }

订购商品类:

class OrderedItem{
private Products productObject;
private int quantity;
ArrayList<ShoppingCart> cart=new ArrayList<ShoppingCart>();
public OrderedItem(){
    productObject=new Products();
} 

public OrderedItem(int quantity, Products productObject) {
    this.quantity = quantity;

}

public void setQuantity(int q){
    quantity=q;
}
public int getQuantity(){
    return quantity;
}

public void setProductObject(Products productObject) {
    this.productObject = productObject;
}

public Products getProductObject() {
    return productObject;
}

}

产品类别:

class Products{
private String productID;
private String name;
private String supplier;
private double price;

public Products(){

}
public Products(String productID,String name,String supplier, double price){
    this.productID=productID;
    this.name=name;
    this.supplier=supplier;
    this.price=price;
}
public void setProductID(String ID){
    productID=ID;
}
public void setName(String newName){
    name=newName;
}
public void setSupplier(String newSupplier){
    supplier=newSupplier;
}
public void setPrice(double newPrice){
    price=newPrice;
}
public String getID(){
    return productID;
}
public String getSupplier(){
    return supplier;
}
public String getNAme(){
    return name;
}
public double getPrice(){
    return price;
}
public String toString(){
    return" Product ID: "+productID+"\n -Product Name: "+name+"\n -Product Supplier: "+supplier+
            "\n -Product Price: "+price+"\n ******************************************";
}

}

帐户类别:

class Account{
private String accountID;
private String username;
private String password;
private Customer robot;
private ShoppingCart relation;
private OrderedItem orders;
private Products PO=new Products(); 

public Account(){

 }
public Account(String id,String userName,String password){
   accountID=id;
   username=userName;
   this.password=password;


 }
public void AddProducts(int q,String ID){
PO.setProductID(ID);
orders=new OrderedItem(q,PO);
 }
public OrderedItem getProduct(){
return orders; 
}
public void setAccountID(String accountID) {
    this.accountID = accountID;
}

public void setUsername(String username) {
    this.username = username;
}

public void setPassword(String password) {
    this.password = password;
}

public String getAccountID() {
    return accountID;
}

public String getUsername() {
    return username;
}

public String getPassword() {
    return password;
}

 public String toString(){
  return "Account ID: "+accountID+"\n Account username: "+username+"\n 
 Account Password: "+password+"\n "
          + "Customer Details for this Account: \n"+" -name: 
 "+robot.getName()+"\n -address: "+robot.getAddress()
         +"\n -email: "+robot.getEmail()+"\n -phone number: 
 "+robot.getPhone()+"\n ****************************" ;
   }
  }

有一个客户类,它具有名称,地址,电话,电子邮件作为数据字段,以及它们的设置器和获取器。

主要:

   public static void main(String[] args) {
   Scanner input1=new Scanner(System.in);
    int ans;
    Store store = new Store("Camera Online Store");
    Products productObject=new Products();
    Account myAccount=new Account();
    String[]splittedInfoProd;
    String[]splittedInfoAcc;
    int Q=0;
    ArrayList<OrderedItem> cart;
    boolean TF=false;

    ArrayList<String>productsList=new ArrayList<String>();
    // Read all products from the products file
    File products = new File("Products.txt"); 
    try(Scanner input = new Scanner(products);) 
    {
      input.useDelimiter(",");
      while(input.hasNextLine()){
         productsList.add(input.nextLine()); 

      }
      input.close();
    }catch(Exception ex){
       System.out.println("Error in Products");
    }
    for(int i = 0; i< productsList.size(); i++) {
    String account=productsList.get(i);
  splittedInfoProd= account.split(",");
  productObject.setProductID(splittedInfoProd[0]);
   productObject.setName(splittedInfoProd[1]); 
  productObject.setSupplier(splittedInfoProd[2]);

  productObject.setPrice(Double.valueOf(splittedInfoProd[3]));
   productObject=new Products(productObject.getID(),productObject.getNAme(),productObject.getSupplier(),productObject.getPrice());


  store.setArrProd(productObject); 
 } System.out.println(productObject.getPrice());

   // Read all accounts from the account file
   File customerFile = new File("Accounts.txt");
   ArrayList<String>accountList=new ArrayList<String>();
   try(Scanner input = new Scanner(customerFile);) 
    {
     input.useDelimiter(",");
      while(input.hasNextLine()){
          accountList.add(input.nextLine());

         );

     } input.close();          
    }catch(Exception ex){
       System.out.println("Error in Accounts");
    }
   for(int i = 0; i< accountList.size(); i++) {
    String account=accountList.get(i);
  splittedInfoAcc= account.split(",");
  myAccount.setAccountID(splittedInfoAcc[0]);
   myAccount.setUsername(splittedInfoAcc[1]);
   myAccount.setPassword(splittedInfoAcc[2]);
   myAccount=new Account(myAccount.getAccountID(),myAccount.getUsername(),myAccount.getPassword());
  store.setArrAcc(myAccount); 
 }


    System.out.println("^^^^^^ Welcome to our "+store.getName()+" ^^^^^");
    System.out.println("*****************************************");

    while(true)
    {
    System.out.println("Are you a customer or an admin?\n  (1) for user \n  (2) for admin\n  (3) to exit");
    Scanner sc = new Scanner (System.in);
    int choice = sc.nextInt();
        switch (choice) {
            case 1: // customer mode
                System.out.println("Enter your login information.");
               System.out.print("Username:");
               String username = sc.next();
               System.out.print("Password:");
               String password = sc.next();
               int accountIndex=-1;

                for (int i = 0; i < accountList.size(); i++) {
                  String[] userData = accountList.get(i).split(",");  
                if(userData[1].equals(username)&& userData[2].equals(password)){
                    accountIndex=i;
                }

                }

               if(accountIndex<0) 
                   System.out.println("Login Failed! Invalid Username and/or Password.\n");
               else{
                    do
                    {
                        System.out.println("Choose the required operations from the list below:\n  (1) Display all products \n  (2) Add a product to your shopping cart by id \n  (3) View the products in your shopping cart \n  (4) Go to checkout\n  (5) Go back to main menu");
                        choice = sc.nextInt();
                        sc.nextLine();
                        if(choice==1)
                        { 
                             System.out.println("The list of available products: \n");
                              for (int i = 0; i < productsList.size(); i++) {
                        System.out.println(productsList.get(i));
                    }


                         }
                        else if (choice == 2) 
                         {
                             System.out.println("Enter the id of the product: "); 
                             String productID=input1.next();
                             for (int i = 0; i < productsList.size(); i++) {
                                 String infoLine=productsList.get(i);
                              String[]CheckID=infoLine.split(",");
                                 if((CheckID[0].equals(productID))){
                                    TF=true;
                                     break;
                                 } 
                                 }if(TF){
                                    System.out.println("Enter the product quantity: ");
                                     Q=input1.nextInt();

                                     myAccount.AddProducts(Q, productID);
                             System.out.println("The Product has been added to your cart");    
                             }else{
                                      System.out.println("Oops! incorrect product ID");
                                 }
                                 double Total=(Q*productObject.getPrice());
                             System.out.println(Total);

                            /* 
                            add a product to shopping cart 
                             ....................
                            */

                         } 
                        else if (choice == 3) 
                         {
                             //cart.add(myAccount.getProduct());
                             //System.out.println(cart);
                            /*

                            if( shoppingcart is Not empty )
                            {
                                display the products in the shopping cart
                                ..............................
                            }

                            */
                        }
                        else if (choice == 4) // checkout
                         {
                            /*

                            if( shoppingcart is Not empty )
                            {
                                print Receipt
                               ..............................
                                Empty the shopping cart
                               ..............................
                            }

                            */
                        }
                        else if(choice == 5) 
                            break;
                        System.out.println("Another user operation? (0) for yes | (1) for No.");
                       ans = sc.nextInt();
                    } while (ans==0);
               }
               break;
            case 2:// Admin mode
                do{
                System.out.println("Choose the required operations from the list below:\n  (1) Display all products \n  (2) Display all accounts\n  
(3) Add a product  \n  (4) Delete a product \n  (5) Go back to main menu");
                choice = sc.nextInt();
                sc.nextLine();
                if(choice==1) { 
                    System.out.println("The list of available products: 
                  \n");
                   for (int i = 0; i < productsList.size(); i++) {
                        System.out.println(productsList.get(i));
                    }
                }
                else if(choice == 2)
                {
                    System.out.println("The list of accounts: \n");
                    for (int i = 0; i < accountList.size(); i++) {
                        System.out.println(accountList.get(i));
                    }
                }
                else if (choice  == 3)
                {
                    // read product details from the admin and add it to 
               the products array list within the store
                    System.out.println("Great! The product has been 
                 added!");
                }
                else if(choice == 4)
                {
                    /*
                    ....................
                    */
                }
                else if(choice == 5) break;
                System.out.println("Another admin operation? (0) for yes| (1) for No");
                ans = sc.nextInt();} while (ans==0);
                break;
            case 3:
                System.out.println("Thanks for visiting our store!");
                System.exit(0);
            default:
                System.out.println("Incorrect Entry! Try agian!");
                break;
        }

    }





}

希望您能帮我提供我的代码,并先谢谢您!

2 个答案:

答案 0 :(得分:1)

我认为问题在于列表未初始化。此外,通常对接口进行编码比对实现进行编码更好,因此以下更改可能会有所帮助:

class Store{
  private String name;
  // use interface and initialize; 
  private final List<Account> arracc = new ArrayList<>();

  //same here
  private final List<Products> arrprod = new ArrayList<>();

  public Store(){

  }

  // return; note this exposes the internal storage, so may be incorrect
 public List<Account> getArracc() {
   return arracc;
 }

 // return the products; again, exposing internals and allows
 //  for anyone who calls getArrprod() to modify the list or the elements,
 //  which breaks encapsulation
 public List<Products> getArrprod() {
    return arrprod;
 }

 ...

我认为第二个问题可以通过重构来解决。

private static loadProducts(Store store) {
    ArrayList<String>productsList=new ArrayList<String>();
    // Read all products from the products file

    File products = new File("Products.txt"); 
    try(Scanner input = new Scanner(products);) 
    {
      input.useDelimiter(",");
      while(input.hasNextLine()){
         productsList.add(input.nextLine()); 

      }
      input.close();
    }catch(Exception ex){
       System.out.println("Error in Products");
    }

    for(int i = 0; i< productsList.size(); i++) {
      String account=productsList.get(i);
      splittedInfoProd= account.split(",");

      String id = splittedInfoProd[0];
      String name = splittedInfoProd[1];
      String supplier = splittedInfoProd[2];
      double price = Double.valueOf(splittedInfoProd[3]));

      Products productObject = new Products (id, name, supplier, price);

      store.setArrProd(productObject); 
   }
}

store将具有全部。

答案 1 :(得分:0)

第二期,

for(int i = 0; i< productsList.size(); i++) {
String account=productsList.get(i);
splittedInfoProd= account.split(",");
productObject.setProductID(splittedInfoProd[0]);
productObject.setName(splittedInfoProd[1]); 
productObject.setSupplier(splittedInfoProd[2]);

productObject.setPrice(Double.valueOf(splittedInfoProd[3]));
productObject=new Products(productObject.getID(),productObject.getNAme(),productObject.getSupplier(),productObject.getPrice());


store.setArrProd(productObject); 
} System.out.println(productObject.getPrice());

您的productObject在OrderedItem类中具有全局范围。因此,在for循环结束时,您的对象将存储最后一个值,并且当您要打印它时,它将打印最后一个值。所有价格,您应该迭代arraylist。

ArrayList<Products> list = store.getArrprod();

for(Products p : list){
   System.out.println(p.getPrice());
}