0

Alright! So I'm still new to Java and we just started learning about Instances and classes this week.

My problem is that my professor assigned a program (that I've already spent around 10 hours on, I've made headway but I'm still having problems) that has slightly vague instructions, and I'm not sure how to incorporate them into my program.

It's a shopping cart program that takes the name, description, price, and quantity of a product. All of these qualities go into the Item2 class, which I'm not having problems with, and then print using the toString() method in the Item2 class.

Next, I take the name and add this to an array in the ShoppingCart2 class (addItems method), and then make the getTotal method that will go through arrayItems, and add up prices of each item (should call calculateUnitTotal() method of each Item object and add up).

My problem is that by trying to call calculateUnitTotal(), I am either getting the error:

non static method cannot be referenced from a static context

or the dereference error.

My professor does not want me to call the units and price objects from the Item2 class, I need to call this method specifically.

I know that I need to create an instance to do this, and that an object can't be converted to a double, but everything I try doesn't seem to work.

I'm not sure what I'm doing wrong. I also know that the code is kinda messy, I tried my best to clean it up. Any advice would be appreciated!

Item2.java:


        class Item2{
            private String productName;
            public class Item2{
            private String productName;
            private String productDesc;
            private double unitPrice;
            private int units;

            public String getProductName(){
                return productName;
            }
            public String getproductDesc(){
                return productDesc;
            }
            public double getUnitPrice(){
                return unitPrice;
            }
            public int getUnits(){
                return units;
            }
            public void setProductName(String newProductName){
                productName = newProductName;
            }
            public void setProductDesc(String newProductDesc){
                productDesc = newProductDesc;
            }
            public void setUnitPrice(double newUnitPrice){
                unitPrice = newUnitPrice;
            }
            public void setUnits(int newUnits){
                units = newUnits;
            }

        void Item2(){
            productName = "";
            productDesc = "";
            unitPrice = -1;
            units = -1;} 

            public void Item2(String newProductName, String newProductDesc, 
            double newUnitPrice, int newUnits) {
                productName = newProductName;
                productDesc = newProductDesc;
                unitPrice = newUnitPrice;
                units = newUnits;
                }

           public double calculateUnitTotal(){
                double total = unitPrice * units;
                return total;
                }

          public String toStrings() {
               NumberFormat fmt = NumberFormat.getCurrencyInstance();
               return (productName + "\t" + fmt.format(unitPrice) + "\t" + 
               units + "\t" + fmt.format(unitPrice * units));
          }
       }

ShoppingCart2.java:

       class ShoppingCart2{
          private String[] arrayItems;
          private int numItems;

          public ShoppingCart2(){
              arrayItems = new String[20];
              numItems = 0;

          }
          public void addItems(String itemName){   
              for(int i = 0; i < numItems; i++){
                  if(numItems==arrayItems.length)
                     System.out.println("Cart is full.");
                  else{
                     arrayItems[numItems]= itemName;
                     numItems++;
                      }
                    }
                 }
         public ShoppingCart2 getTotal(){
              ShoppingCart2 total = new ShoppingCart2();

              for(int i = 0; i < numItems; i++){
               /////I've tried several different methods here, they always 
                 ////lead to either 
                 /// a need to dereference or the non static method error
               }
              return total;}

        public String toString() {
             NumberFormat fmt = NumberFormat.getCurrencyInstance();

             String cart = "\nShopping Cart\n";

             for (int i = 0; i < numItems; i++)
                  cart += arrayItems[i] + "\n";

                  cart += "\nTotal Price: " + fmt.format(total);
                  cart += "\n";

                  return cart;
             }
           }

I expect the output to be the names of the items in the array and the total of all the items.

acarlstein
  • 1,799
  • 2
  • 13
  • 21
Darian Ray
  • 15
  • 5
  • In Item2 class, change the method `toStrings()` to `toString()` – acarlstein Apr 22 '19 at 19:23
  • In the ShoppingCart2 class, I don't see you using Item2 to store the values as instructed `It's a shopping cart program that takes the name, description, price, and quantity of a product. All of these qualities go into the Item2 class` – acarlstein Apr 22 '19 at 19:25
  • I'm not sure what you mean besides the fact that I haven't added the description in the toString method yet? I had originally overlooked that and got sidetracked with the error I've been having. And the reason I have it named toStrings is because there's two methods and I had somehow used the incorrect one in the main. i'll go ahead and change that back. – Darian Ray Apr 22 '19 at 19:27
  • I wrote you the answer. Check it out and vote if it helps. – acarlstein Apr 22 '19 at 19:39
  • I'll check it out, and thank you so much for the help! – Darian Ray Apr 22 '19 at 19:43

1 Answers1

0

It sounds to me that the idea is to use Item2 class to encapsulate all the properties, and then use ShoppingCart2 to administrate what do you with them.

So, your ShoppingCart2 may have to look like:

class ShoppingCart{
  private ArrayList<Item2> items;

  public ShoppingCart2(){
    items = new ArrayList<Item2>();
  }

  public void addItem(Item2 item){
    items.add(item);
  }

  public void addItems(ArrayList<Items> items){
    this.items.addAll(items)
  }

  public double getTotal(){
    double total = 0L;
    for(Item2 item : items){      
      total += item.calculateUnitTotal();
    }
    return total;
  }

  public String toString(){
     StringBuffer sb = new StringBuffer();
     for (Item2 item: items){
       // Print each item here
       sb.append(item.toString());
       sb.append("----------------\n");
     }
     sb.append("*************");
     sb.append("Total Price: ");
     sb.append(getTotal());
     return sb.toString();     
  }
}

Note: this code wasn't fully tested.

* UPDATE *

A closer look shows that your Item2 class is wrong. Here is a cleaner version.

class Item2 {
    private String productName;
    private String productDesc;
    private double unitPrice;
    private int units;

    public Item2(){
        productName = "";
        productDesc = "";
        unitPrice = -1;
        units = -1;
    } 

    public Item2(String newProductName, 
                String newProductDesc, 
                double newUnitPrice, 
                int newUnits) {
        productName = newProductName;
        productDesc = newProductDesc;
        unitPrice = newUnitPrice;
        units = newUnits;
    }

    public String getProductName(){
        return productName;
    }
    public String getproductDesc(){
        return productDesc;
    }
    public double getUnitPrice(){
        return unitPrice;
    }
    public int getUnits(){
        return units;
    }
    public void setProductName(String newProductName){
        productName = newProductName;
    }
    public void setProductDesc(String newProductDesc){
        productDesc = newProductDesc;
    }
    public void setUnitPrice(double newUnitPrice){
        unitPrice = newUnitPrice;
    }
    public void setUnits(int newUnits){
        units = newUnits;
    }

    public double calculateUnitTotal(){
        return unitPrice * (double) units;
    }

    public String toString() {
       NumberFormat fmt = NumberFormat.getCurrencyInstance();
       StringJoiner sj = new StringJoiner("\t");
       sj.add(productName).add(unitPrice).add(units).add(fmt.format(unitPrice * units));      
       return sj.toString();
    }   
}

Some Explanation

The reason you wish to use StringJoiner or StringBuffer when concatenating strings is that it way more efficient then using the plus sign + operator.

The plus operator create a lot of overhead since it takes two parameters, strings, and create a brand new string from them.

StringBuffer and StringJoiner allows you to add the strings and in the last moment, you can turn them all together into a string.

acarlstein
  • 1,799
  • 2
  • 13
  • 21
  • If you need an extra explanation of what it is done in the code, let me know. – acarlstein Apr 22 '19 at 19:38
  • I tried it out and unfortunately I don't think I can use the code for getTotal, he wants us to call calculateUnitTotal() specifically. I could definitely just use that though if I need to, plus he may have mistyped the directions again. Thank you for your advice anyhow and sorry about that. (: – Darian Ray Apr 22 '19 at 19:58
  • Even better! I changed the code to use `calculateUnitTotal()` – acarlstein Apr 23 '19 at 13:00
  • The important thing here is to understand the basic concepts of Data Structure. In this case, you are applying encapsulation in the class Item2. In ShoppingCard2, you are learning about Collections with the ArrayList, how to iterate the collection directly with the loop and to use them together to obtain a result. – acarlstein Apr 23 '19 at 13:04
  • I would advice you to check some documentation and videos, online, about Data Structures and Object Oriented Programming using Java. – acarlstein Apr 23 '19 at 13:25
  • Sorry for the late reply! Thank you so much for the help with this, it's really helped me understand these topics better. I really appreciate it and I will be looking further into Data Structures and OOP in Java! (: – Darian Ray Apr 23 '19 at 17:22
  • @DarianRay Glad it did help you. Don't forget to vote ;) – acarlstein Apr 23 '19 at 17:37