-3

So I've been working on an online shopping store program, it has a products,accounts,ordered items,shopping cart classes as well as a store class that contains an array list of products and accounts, I've read some information about products and accounts from files and stored them in products and accounts objects,

(this is segment of the file to show you how it looks) 0001,Nikon D3300 w/ AF-P DX 18-55mm VR Digital SLR,Nikon,396.95,

0002,Canon EOS Rebel T6 Digital SLR Camera Kit with EF-S 18-55mm f/3.5-5.6 IS II Lens,Canon,400.95,

I'm suppose to add these objects to my array lists that i mentioned earlier but it gives me this error:

Exception in thread "main" java.lang.NullPointerException at programming2projectmain.Store.setArrProd(Programming2ProjectMain.java:462) at programming2projectmain.Programming2ProjectMain.main(Programming2ProjectMain.java:69)

line 69: store.setArrProd(productObject);

and in store class:

public void setArrProd(Products x){

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

and for the second problem with mu program is that when I read products info (in a for loop) I read prices too, i tried printing them so i can see what have been stored and what's not.. basically when printing inside the loop it prints all prices as it suppose but once i get it out it only prints the last one.. and that's a problem for me cause i need each product's price to calculate the total of products in my shopping cart which i also don't know how to get the specific price for the item that have been added...

This is my store class:

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;
}

}

shopping cart class:

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

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

ordered items class:

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;
}

}

product class:

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 ******************************************";
}

}

account class:

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 ****************************" ;
   }
  }

and there is a customer class that have name,address,phone,email as data fields and their setters and getters and that's it.

Main:

   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;
        }

    }





}

hope you help me with my code and thank you in advance!

  • There is a lot of code here, but from a quick look, the error is in `arrprod.add(x);`, and the class `Store` declared but never initialized the `arrprod` variable. Try `private ArrayList arrprod = new ArrayList<>();` (you'll need to do it for the other one as well). Note that if you initialized them somewhere else, I apologize for missing it. – KevinO Mar 28 '19 at 05:20
  • There is confusion in the code. There is an instance variable `productObject` in `main`, and then it is also declared in the `for` loop, and there is setting of a the object, and creating a new one. The reading of the product file needs to a)be moved to a separate method, and b)be cleaned up. – KevinO Mar 28 '19 at 05:33

2 Answers2

1

I believe the issue to be that the lists are not initialized. In addition, it is generally better to code to an interface than an implementation, so the following changes might help:

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;
 }

 ...

I think the second issue can be addressed with some refactoring.

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); 
   }
}

The store will have all of the entires.

KevinO
  • 4,303
  • 4
  • 27
  • 36
0

For your second issue,

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());

Your productObject has global decleration in the OrderedItem class.So at the end of your for loop, your object will store the last values and when you want to print it,it will print the last value.To get all prices,you should iterate arraylist.

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

for(Products p : list){
   System.out.println(p.getPrice());
}
Y.Kakdas
  • 833
  • 7
  • 17
  • but what if i want to print only one specific price for a specific item in the list? – AmoonAhmed93 Mar 28 '19 at 06:29
  • I assume that productId is unique,in other words it is key by database terms.So when you iterate arraylist,you can add statement like if(productId.equals(something)),then get the price,or you can create new list for prices and add the prices for items that you want in your for loop like store.setArrProd. – Y.Kakdas Mar 28 '19 at 06:42