Hello,

I am having trouble sorting my array. I have gotten it to read out just the names in ABC order, but I need it to display all of the attributes. I have read several sites trying to figure out how to do it and I keep getting errors. Here is my code, can anyone help me atleast understand if I am putting the code in the right spot. Most websites show sort() in its own file not being added to one. Thanks.

package inventory;
import java.text.DecimalFormat;
import java.util.Arrays;
/**
 *
 * @author Mel
 */
class Pizza {
    // Private variables
    private String name;
    private int quantity;
    private double price;
    private int productNumber = 0;

    // Default constructor uses other constructor to set the
    // default state of the object.

    public Pizza() {
        this(0,"Unknown",0,0.00);
    }

    // Constructor that user can specify a name, quantity, and price for items.
    public Pizza(int productNumber, String itemname, int quantityOnHand, double itemprice) {
        productNumber = productNumber;
        setName(itemname);
        setQuantityOnHand(quantityOnHand);
        setPrice(itemprice);
    }


    // Public mutators (changes state of the object)
    public void setName(String itemname) {
        name = itemname;
    }


    // Sets quantity on hand and if negative, defaults to zero.
    public void setQuantityOnHand(int quantityOnHand) {
        if (quantityOnHand > 0) {
            quantity = quantityOnHand;
        }
        else { quantity = 0; }
    }


    // Set price of a product and defaults it to zero if negative.
    public void setPrice(double itemPrice) {
        if (itemPrice > 0.00) {
            price = itemPrice;
        }
        else { price = 0.00; }
    }

    // Get the product's name
    public String getName() {
        return name;
    }

    public int getQuantityOnHand() {
        return quantity;
    }

    public double getPrice() {
        return price;
    }

    // Calculate the value of stock on this particular item.
    public double getItemValue() {
        return (price * (double)quantity);
    }

    // String representation of the product
    public String toString() {
        return name + " - " + price;
    }
}
public class Inventory {
    // Setup an array of Products (set it to hold 30 items)
    int inventorySize = 30;
    private Pizza items[] = new Pizza[inventorySize];

    // Set the formatter to format values into currency form.
    DecimalFormat formatter = new DecimalFormat("$##,###.00");

    // Adds a product to the array of pizza. Adds to first empty slot found.
    public void addPizza(Pizza item) {
        for (int i = 0; i < inventorySize; i++) {
            if (items[i] == null) {
                items[i] = item;
                 return;
            }
        }
    }

    // Loop through our array of pizza and add up the total value.
    // Go item by item adding the quantity on hand x its price.
    // Add that value to a running total variable.

    public double getTotalInvValue() {
        double sumOfInventory = 0.0;

        // Uses a  for loop which iterates the array of items.
        for (Pizza item : items) {

            if (item != null) {
                sumOfInventory += item.getItemValue();
           }
        }
        return sumOfInventory;
    }

    // Prints the inventory list including name, quantity, price, and total stock value for each item.
    public void printInventory() {
        System.out.println("Printing items in inventory...\n");

        boolean hasItems = false;

        for (Pizza item : items) {
            if (item != null) {
                hasItems = true;
                System.out.println(item.toString() + " Quantity: " + item.getQuantityOnHand() + " Value of Stock: " + formatter.format(item.getItemValue()));
            }
        } 

        // If no items were found, print a message saying the inventory is empty.
        if (!hasItems) { System.out.println("Inventory is empty at the moment.\n"); }
    }
}
// Inherited class PizzaRestock from the base class Pizza


class PizzaRestock extends Pizza {
    // Holds the year the move was made
    private String supplier;



    public PizzaRestock(int productNumber, String itemname, int quantityOnHand, double itemprice, String supplier) {
        // Pass on the values needed for creating the Product class first thing
        super(productNumber, itemname, quantityOnHand, itemprice);
        supplier = "";
    }

      // Get the supplier of this Pizza product
    public String getSupplier() {
        return supplier;
    }

    // Overrides getItemValue() in Product class by calling the base class version and
    // adding a 5% restocking fee on top
    public double getItemValue() {
        return super.getItemValue() * 1.05;
    }

    // Simply gets the base class's value, and figures out the 5% restocking fee only
    public double getRestockingFee() {
        return super.getItemValue() * .05;
    }
}

class InventoryTest {

     static DecimalFormat formatter = new DecimalFormat("$##,###.00");

    public static void main(String args[]) {

       Pizza item1 = new Pizza(1234, "Dough", 22, 1.99);
       Pizza item2 = new Pizza(1235, "Sauce", 35, 5.99);
       Pizza item3 = new Pizza(1236, "Cheese", 4, 15.99);
       Pizza item4 = new Pizza(1237, "Pepperoni", 3, 14.99);
       Pizza item5 = new Pizza(1238, "Ham", 2, 16.99);

    PizzaArray.sort(function(a,b){
        var nameA=a.name.toLowerCase();, nameB=b.name.toLowerCase();
        if (nameA < nameB); //sort string ascending
            return -1;
        if (nameA > nameB);
            return 1;
            return 0;//default return value (no sorting)
        });


        // Create an inventory item to store our products
        Inventory myPizza = new Inventory();

        // Let's show there is nothing in the inventory to start.
        myPizza.printInventory();

        // Now lets add the items we declared above.
        myPizza.addPizza(item1);
        myPizza.addPizza(item2);
        myPizza.addPizza(item3);
        myPizza.addPizza(item4);
        myPizza.addPizza(item5);

        // Print out the inventory
        myPizza.printInventory();

        // Print the total value of the inventory
        // (after formatted using DecimalFormat class into dollars and cents)
        System.out.println("\nTotal value of inventory is: " + formatter.format(myPizza.getTotalInvValue()));




    }
}

Recommended Answers

All 22 Replies

Line 173 etc... is that Java?

Yes, I was looking up how to add a sort to an array that is already existing.

Let me re-phrase that...

The code starting at line 173 is not Java code.

commented: nice one :) +13

I think you'll find that the code you have used in that specific section is not Java, but JavaScript, a completely unrelated language despite its name. Java does not have a function keyword, among other things.

(On an unrelated note, I might add that your screen name is somewhat... unnerving to me. Perhaps I've watched too movies like WarGames and By Dawn's Early Light too many times.)

Yes.

Anyway, rather than blindly copying some random code from the web, learn how to sort arrays of objects and write it yourself. The key to sorting objects is a Comparator - which defines the order in which the objects are to be sorted (eg by name, price weight etc). Here is a very good tutorial that will teach you what you need to know (you can ignore part 3 of that for now).

First off I did not copy paste the code, and it came from Java for complete beginners. That sucks that it wasn't even Java, so thank you for the information. Thanks for the link JamesCherrill. And Schol-R-LEA I am sorry you don't like my name. I have used it for many years and really just came up with it.

Also I am reading the link you posted. What I am confused about is do I need to make a new array in place of the one that is currently in my code to accomidate the sort?

No (unless you want to keep the original order as well). Arrays.sort will just sort the existing array according to your comparator. It doesn't create a new array.

And Schol-R-LEA I am sorry you don't like my name. I have used it for many years and really just came up with it.

Oh, no worries. I actually like it, but it just seems a bit ominous to me as someone who grew up in the 1970s and 1980s. I don't know if you even know what the MX missile was...

Ok thank you, but I am still having trouble because I don't know where to put the code. Does it go near the array or just anywhere that is not in another class?

It doesn't really matter, as long as its somewhere where you can access the array. Inside the Inventory class would be an obvious choice.

Ok and I did try that but since it has the public static void main(String[] args) I get an error. Is it possible to not have that part in the code?

Never just say "I get an error". Help us to help you by copy/pasting the complete error message!
Anyway, without knowing what code you tried to put where nobody can say why it's wrong.

ps: I'm away now until tomorrow, but maybe someone else can step in, thanks. J

Ok thank you very much for your help :)

Ok so if anyone else can help me I am having trouble getting the sort array to work. Here is my code so far. Am I completely off or on the right track? The problem I am having is in the return p1.name- p2.name; it says that name is private in the Pizza class, but I thought by declaring it again in the sort array it would work.

package inventory;
import java.text.DecimalFormat;
import java.util.Arrays;
import java.util.Comparator;



/**
 *
 * @author Mel
 */
class Pizza {
    // Private variables
    private String name;
    private int quantity;
    private double price;
    private int productNumber = 0;

    // Default constructor uses other constructor to set the
    // default state of the object.

    public Pizza() {
        this(0,"Unknown",0,0.00);
    }

    // Constructor that user can specify a name, quantity, and price for items.
    public Pizza(int productNumber, String itemname, int quantityOnHand, double itemprice) {
        productNumber = productNumber;
        setName(itemname);
        setQuantityOnHand(quantityOnHand);
        setPrice(itemprice);
    }


    // Public mutators (changes state of the object)
    public void setName(String itemname) {
        name = itemname;
    }


    // Sets quantity on hand and if negative, defaults to zero.
    public void setQuantityOnHand(int quantityOnHand) {
        if (quantityOnHand > 0) {
            quantity = quantityOnHand;
        }
        else { quantity = 0; }
    }


    // Set price of a product and defaults it to zero if negative.
    public void setPrice(double itemPrice) {
        if (itemPrice > 0.00) {
            price = itemPrice;
        }
        else { price = 0.00; }
    }

    // Get the product's name
    public String getName() {
        return name;
    }

    public int getQuantityOnHand() {
        return quantity;
    }

    public double getPrice() {
        return price;
    }

    // Calculate the value of stock on this particular item.
    public double getItemValue() {
        return (price * (double)quantity);
    }

    // String representation of the product
    public String toString() {
        return name + " - " + price;
    }
}
public class Inventory {
    // Setup an array of Products (set it to hold 30 items)
    int inventorySize = 30;
    private Pizza items[] = new Pizza[inventorySize];

    // Set the formatter to format values into currency form.
    DecimalFormat formatter = new DecimalFormat("$##,###.00");

    // Adds a product to the array of pizza. Adds to first empty slot found.
    public void addPizza(Pizza item) {
        for (int i = 0; i < inventorySize; i++) {
            if (items[i] == null) {
                items[i] = item;
                 return;
            }
        }
    }

    // Loop through our array of pizza and add up the total value.
    // Go item by item adding the quantity on hand x its price.
    // Add that value to a running total variable.

    public double getTotalInvValue() {
        double sumOfInventory = 0.0;

        // Uses a  for loop which iterates the array of items.
        for (Pizza item : items) {

            if (item != null) {
                sumOfInventory += item.getItemValue();
           }
        }
        return sumOfInventory;
    }

    // Prints the inventory list including name, quantity, price, and total stock value for each item.
    public void printInventory() {
        System.out.println("Printing items in inventory...\n");

        boolean hasItems = false;

        for (Pizza item : items) {
            if (item != null) {
                hasItems = true;
                System.out.println(item.toString() + " Quantity: " + item.getQuantityOnHand() + " Value of Stock: " + formatter.format(item.getItemValue()));
            }
        } 

        // If no items were found, print a message saying the inventory is empty.
        if (!hasItems) { System.out.println("Inventory is empty at the moment.\n"); }
    }

}
// Inherited class PizzaRestock from the base class Pizza


class PizzaRestock extends Pizza {
    // Holds the year the move was made
    private String supplier;



    public PizzaRestock(int productNumber, String itemname, int quantityOnHand, double itemprice, String supplier) {
        // Pass on the values needed for creating the Product class first thing
        super(productNumber, itemname, quantityOnHand, itemprice);
        supplier = "";
    }

      // Get the supplier of this Pizza product
    public String getSupplier() {
        return supplier;
    }

    // Overrides getItemValue() in Product class by calling the base class version and
    // adding a 5% restocking fee on top
    public double getItemValue() {
        return super.getItemValue() * 1.05;
    }

    // Simply gets the base class's value, and figures out the 5% restocking fee only
    public double getRestockingFee() {
        return super.getItemValue() * .05;
    }
}

class InventoryTest {

     static DecimalFormat formatter = new DecimalFormat("$##,###.00");

    public static void main(String args[]) {


       Pizza item1 = new Pizza(1234, "Dough", 22, 1.99);
       Pizza item2 = new Pizza(1235, "Sauce", 35, 5.99);
       Pizza item3 = new Pizza(1236, "Cheese", 4, 15.99);
       Pizza item4 = new Pizza(1237, "Pepperoni", 3, 14.99);
       Pizza item5 = new Pizza(1238, "Ham", 2, 16.99);



        // Create an inventory item to store our products
        Inventory myPizza = new Inventory();

        // Let's show there is nothing in the inventory to start.
        myPizza.printInventory();

        // Now lets add the items we declared above.
        myPizza.addPizza(item1);
        myPizza.addPizza(item2);
        myPizza.addPizza(item3);
        myPizza.addPizza(item4);
        myPizza.addPizza(item5);

        // Print out the inventory
        myPizza.printInventory();

        // Print the total value of the inventory
        // (after formatted using DecimalFormat class into dollars and cents)
        System.out.println("\nTotal value of inventory is: " + formatter.format(myPizza.getTotalInvValue()));
    }


class PizzaSort{
    String name;
    public PizzaSort(String n){
        name = n;
    }
}
class PizzaSortNameComparator implements Comparator<Pizza>{

    @Override
    public int compare(Pizza p1, Pizza p2){
        return p1.name - p2.name;
    }
}
class ArraySort {


        Pizza p1 = new Pizza(2);
        Pizza p2 = new Pizza(1);


        Pizza[] pizzaArray = {p1, p2};
        printPizzas(pizzaArray);

        Arrays.sort(pizzaArray, new PizzaNameComparator()); 
        printPizzas(pizzaArray);
    }

    public static void printPizza(Pizza[] pizzas){
        for(Pizza p: pizza)
            System.out.print(p.name + " " );

        System.out.println();
    }
}

Not quite gone yet...

yes, thebname variable is private (that's good), but you have a public getName() method to access it (also good). Use the public method.

In your compare method you need to compare the names, you can't just subtract one from the other. The String class has a conpareTo method that will do the trick.

Ok I have the code building without errors now, but the sort array is not working. Can anyone help me understand why? Here is the new code.

package inventory;
import java.text.DecimalFormat;
import java.util.Arrays;
import java.util.Comparator;



/**
 *
 * @author Mel
 */
class Pizza {
    // Private variables
    private String name;
    private int quantity;
    private double price;
    private int productNumber = 0;

    // Default constructor uses other constructor to set the
    // default state of the object.

    public Pizza() {
        this(0,"Unknown",0,0.00);
    }

    // Constructor that user can specify a name, quantity, and price for items.
    public Pizza(int productNumber, String itemname, int quantityOnHand, double itemprice) {
        productNumber = productNumber;
        setName(itemname);
        setQuantityOnHand(quantityOnHand);
        setPrice(itemprice);
    }


    // Public mutators (changes state of the object)
    public void setName(String itemname) {
        name = itemname;
    }


    // Sets quantity on hand and if negative, defaults to zero.
    public void setQuantityOnHand(int quantityOnHand) {
        if (quantityOnHand > 0) {
            quantity = quantityOnHand;
        }
        else { quantity = 0; }
    }


    // Set price of a product and defaults it to zero if negative.
    public void setPrice(double itemPrice) {
        if (itemPrice > 0.00) {
            price = itemPrice;
        }
        else { price = 0.00; }
    }

    // Get the product's name
    public String getName() {
        return name;
    }

    public int getQuantityOnHand() {
        return quantity;
    }

    public double getPrice() {
        return price;
    }

    // Calculate the value of stock on this particular item.
    public double getItemValue() {
        return (price * (double)quantity);
    }

    // String representation of the product
    public String toString() {
        return name + " - " + price;
    }
}
public class Inventory {
    // Setup an array of Products (set it to hold 30 items)
    int inventorySize = 30;
    private Pizza items[] = new Pizza[inventorySize];

    // Set the formatter to format values into currency form.
    DecimalFormat formatter = new DecimalFormat("$##,###.00");

    // Adds a product to the array of pizza. Adds to first empty slot found.
    public void addPizza(Pizza item) {
        for (int i = 0; i < inventorySize; i++) {
            if (items[i] == null) {
                items[i] = item;
                 return;
            }
        }
    }

    // Loop through our array of pizza and add up the total value.
    // Go item by item adding the quantity on hand x its price.
    // Add that value to a running total variable.

    public double getTotalInvValue() {
        double sumOfInventory = 0.0;

        // Uses a  for loop which iterates the array of items.
        for (Pizza item : items) {

            if (item != null) {
                sumOfInventory += item.getItemValue();
           }
        }
        return sumOfInventory;
    }

    // Prints the inventory list including name, quantity, price, and total stock value for each item.
    public void printInventory() {
        System.out.println("Printing items in inventory...\n");

        boolean hasItems = false;

        for (Pizza item : items) {
            if (item != null) {
                hasItems = true;
                System.out.println(item.toString() + " Quantity: " + item.getQuantityOnHand() + " Value of Stock: " + formatter.format(item.getItemValue()));
            }
        } 

        // If no items were found, print a message saying the inventory is empty.
        if (!hasItems) { System.out.println("Inventory is empty at the moment.\n"); }
    }

}
// Inherited class PizzaRestock from the base class Pizza


class PizzaRestock extends Pizza {
    // Holds the year the move was made
    private String supplier;



    public PizzaRestock(int productNumber, String itemname, int quantityOnHand, double itemprice, String supplier) {
        // Pass on the values needed for creating the Product class first thing
        super(productNumber, itemname, quantityOnHand, itemprice);
        supplier = "";
    }

      // Get the supplier of this Pizza product
    public String getSupplier() {
        return supplier;
    }

    // Overrides getItemValue() in Product class by calling the base class version and
    // adding a 5% restocking fee on top
    @Override
    public double getItemValue() {
        return super.getItemValue() * 1.05;
    }

    // Simply gets the base class's value, and figures out the 5% restocking fee only
    public double getRestockingFee() {
        return super.getItemValue() * .05;
    }
}

class InventoryTest {

     static DecimalFormat formatter = new DecimalFormat("$##,###.00");

    public static void main(String args[]) {


       Pizza item1 = new Pizza(1234, "Dough", 22, 1.99);
       Pizza item2 = new Pizza(1235, "Sauce", 35, 5.99);
       Pizza item3 = new Pizza(1236, "Cheese", 4, 15.99);
       Pizza item4 = new Pizza(1237, "Pepperoni", 3, 14.99);
       Pizza item5 = new Pizza(1238, "Ham", 2, 16.99);



        // Create an inventory item to store our products
        Inventory myPizza = new Inventory();

        // Let's show there is nothing in the inventory to start.
        myPizza.printInventory();

        // Now lets add the items we declared above.
        myPizza.addPizza(item1);
        myPizza.addPizza(item2);
        myPizza.addPizza(item3);
        myPizza.addPizza(item4);
        myPizza.addPizza(item5);

        // Print out the inventory
        myPizza.printInventory();

        // Print the total value of the inventory
        // (after formatted using DecimalFormat class into dollars and cents)
        System.out.println("\nTotal value of inventory is: " + formatter.format(myPizza.getTotalInvValue()));
    }


class PizzaSort{
    String getName;
    public PizzaSort(String n){
       getName = n;
    }
}
class PizzaSortNameComparator implements Comparator<Pizza>{

    @Override
    public int compare(Pizza item1, Pizza item2){
        return (item1.getName().compareTo(item2.getName()));
    }
}
class ArraySort {


        Pizza item1 = new Pizza();
        Pizza item2 = new Pizza();


        Pizza[] pizzaArray = {item1, item2};

    }

    public static void printPizza(Pizza[] pizzaArray){
        for(Pizza p: pizzaArray)
            System.out.print(p.getName() + " " );

        System.out.println();
    }
}

Hello, its an basic example maked for you, here u can add more logical rules.
Collections Offer an method called "sort" that applies only in List and subclasses, but u need implements the class Comparable and override method compareTo. Here i use Comparable instead Comparable<BasicPizza>, but you can use both.
Here is BasicPizza class:

package daniweb;

/**
 *
 * @author JoZulyk http://inovawebstudio.com
 */
public class BasicPizza implements Comparable{
    private String name;

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

    @Override
    public int compareTo(Object o) {
        int val = this.getName().compareTo(((BasicPizza)o).getName());
        return val;
    }
}

And here is the main class:

package daniweb;

import java.util.ArrayList;
import java.util.Collections;

/**
 *
 * @author JoZulyk http://inovawebstudio.com
 */
public class MainBasicPizza {
    public static void main(String [] argv ){
        ArrayList pizzas = new ArrayList<>();
        //By FirtsLetter
        pizzas.add(new BasicPizza("Devore"));
        pizzas.add(new BasicPizza("Brain"));
        pizzas.add(new BasicPizza("Charlotte"));
        pizzas.add(new BasicPizza("Adam"));
        //By TwoFirstLetter
        pizzas.add(new BasicPizza("Marmota"));
        pizzas.add(new BasicPizza("Manicura"));
        pizzas.add(new BasicPizza("Mazpan"));
        pizzas.add(new BasicPizza("Maco"));
        //printing unsorted List //before sort
        System.out.println("ArrayList is unsort");
        for(Object bp : pizzas){
            System.out.println("Pizzas Name: "+ ((BasicPizza)bp).getName());
        }
        //start the sort
        Collections.sort(pizzas);
        //after sort
        System.out.println("ArrayList is sorted");
        for(Object bp : pizzas){
            System.out.println("Pizzas Name: "+ ((BasicPizza)bp).getName());
        }
    }
}

The output is:

ArrayList is unsort
Pizzas Name: Devore
Pizzas Name: Brain
Pizzas Name: Charlotte
Pizzas Name: Adam
Pizzas Name: Marmota
Pizzas Name: Manicura
Pizzas Name: Mazpan
Pizzas Name: Maco
ArrayList is sorted
Pizzas Name: Adam
Pizzas Name: Brain
Pizzas Name: Charlotte
Pizzas Name: Devore
Pizzas Name: Maco
Pizzas Name: Manicura
Pizzas Name: Marmota
Pizzas Name: Mazpan

now, is ur responsability make changes, add more logical rules, use objects, etc. Is all. Bye

Ok thank you for the help, but I believe that we are supposed to make the sort array print out not just the name but the all the parameters. How can I get that output because I have had the output you showed above but got it wrong. Thanks!

You have a toString() method in you Pizza class(es). Java will automatically use that when you try to print a Pizza - ie it will print the result of calling toString() for each Pizza.

    for(Object bp : pizzas) {
        System.out.println("Pizza: "+ bp);
    }

I am feeling like a dumb dumb, but I still cannot get the code to work. I am not getting any errors, but the output is not changing. Here is the code.

package inventory;
import java.text.DecimalFormat;
import java.util.Collections;
import java.util.ArrayList;



/**
 *
 * @author Mel
 */
class Pizza {
    // Private variables
    private String name;
    private int quantity;
    private double price;
    private int productNumber = 0;

    // Default constructor uses other constructor to set the
    // default state of the object.

    public Pizza() {
        this(0,"Unknown",0,0.00);
    }

    // Constructor that user can specify a name, quantity, and price for items.
    public Pizza(int productNumber, String itemname, int quantityOnHand, double itemprice) {
        productNumber = productNumber;
        setName(itemname);
        setQuantityOnHand(quantityOnHand);
        setPrice(itemprice);
    }


    // Public mutators (changes state of the object)
    public void setName(String itemname) {
        name = itemname;
    }


    // Sets quantity on hand and if negative, defaults to zero.
    public void setQuantityOnHand(int quantityOnHand) {
        if (quantityOnHand > 0) {
            quantity = quantityOnHand;
        }
        else { quantity = 0; }
    }


    // Set price of a product and defaults it to zero if negative.
    public void setPrice(double itemPrice) {
        if (itemPrice > 0.00) {
            price = itemPrice;
        }
        else { price = 0.00; }
    }

    // Get the product's name
    public String getName() {
        return name;
    }

    public int getQuantityOnHand() {
        return quantity;
    }

    public double getPrice() {
        return price;
    }

    // Calculate the value of stock on this particular item.
    public double getItemValue() {
        return (price * (double)quantity);
    }

    // String representation of the product
    public String toString() {
        return name + " - " + price;
    }
}
public class Inventory {
    // Setup an array of Products (set it to hold 5 items)
    int inventorySize = 5;
    private Pizza items[] = new Pizza[inventorySize];

    // Set the formatter to format values into currency form.
    DecimalFormat formatter = new DecimalFormat("$##,###.00");

    // Adds a product to the array of pizza. Adds to first empty slot found.
    public void addPizza(Pizza item) {
        for (int i = 0; i < inventorySize; i++) {
            if (items[i] == null) {
                items[i] = item;
                 return;
            }
        }
    }

    // Loop through our array of pizza and add up the total value.
    // Go item by item adding the quantity on hand x its price.
    // Add that value to a running total variable.
 class BasicPizza implements Comparable{
    private String name;
    public BasicPizza(String name){
        this.name = name;
    }
    public String getName(){
        return name;
    }
    public void setName(String name){
        this.name = name;
    }
    @Override
    public int compareTo(Object o) {
        int val = this.getName().compareTo(((BasicPizza)o).getName());
        return val;
    }
}
    public double getTotalInvValue() {
        double sumOfInventory = 0.0;

        // Uses a  for loop which iterates the array of items.
        for (Pizza item : items) {

            if (item != null) {
                sumOfInventory += item.getItemValue();
           }
        }
        return sumOfInventory;
    }

    // Prints the inventory list including name, quantity, price, and total stock value for each item.
    public void printInventory() {
        System.out.println("Printing items in inventory...\n");

        boolean hasItems = false;

        for (Pizza item : items) {
            if (item != null) {
                hasItems = true;
                System.out.println(item.toString() + " Quantity: " + item.getQuantityOnHand() + " Value of Stock: " + formatter.format(item.getItemValue()));
            }
        } 

        // If no items were found, print a message saying the inventory is empty.
        if (!hasItems) { System.out.println("Inventory is empty at the moment.\n"); }
    }
}
// Inherited class PizzaRestock from the base class Pizza

class PizzaRestock extends Pizza {
    private String supplier;

public PizzaRestock(int productNumber, String itemname, int quantityOnHand, double itemprice, String supplier) {
        // Pass on the values needed for creating the Pizza class first thing
        super(productNumber, itemname, quantityOnHand, itemprice);
        supplier = "";
    }

      // Get the supplier of this Pizza product
    public String getSupplier() {
        return supplier;
    }

    // Overrides getItemValue() in Pizza class by calling the base class version and
    // adding a 5% restocking fee on top
    @Override
    public double getItemValue() {
        return super.getItemValue() * 1.05;
    }

    // Simply gets the base class's value, and figures out the 5% restocking fee only
    public double getRestockingFee() {
        return super.getItemValue() * .05;
    }
}

class InventoryTest {

     static DecimalFormat formatter = new DecimalFormat("$##,###.00");

    public static void main(String args[]) {


       Pizza item1 = new Pizza(1234, "Dough", 22, 1.99);
       Pizza item2 = new Pizza(1235, "Sauce", 35, 5.99);
       Pizza item3 = new Pizza(1236, "Cheese", 4, 15.99);
       Pizza item4 = new Pizza(1237, "Pepperoni", 3, 14.99);
       Pizza item5 = new Pizza(1238, "Ham", 2, 16.99);

    // Create an inventory item to store our products
        Inventory myPizza = new Inventory();

        // Let's show there is nothing in the inventory to start.
        myPizza.printInventory();

        // Now lets add the items we declared above.
        myPizza.addPizza(item1);
        myPizza.addPizza(item2);
        myPizza.addPizza(item3);
        myPizza.addPizza(item4);
        myPizza.addPizza(item5);

        // Print out the inventory
        myPizza.printInventory();

        // Print the total value of the inventory
        // (after formatted using DecimalFormat class into dollars and cents)
        System.out.println("\nTotal value of inventory is: " + formatter.format(myPizza.getTotalInvValue()));
    }
}
class BasicPizza implements Comparable{
    private String name;
    public BasicPizza(String name){
        this.name = name;
    }
    public String getName(){
        return name;
    }
    public void setName(String name){
        this.name = name;
    }
    @Override
    public int compareTo(Object o) {
        int val = this.getName().compareTo(((BasicPizza)o).getName());
        return val;
    }
}

class MainBasicPizza {
    public static void main(String [] argv ){
        ArrayList pizzas = new ArrayList<>();
        //By FirtsLetter
        pizzas.add(new BasicPizza("Dough"));
        pizzas.add(new BasicPizza("Sauce"));
        pizzas.add(new BasicPizza("Cheese"));
        pizzas.add(new BasicPizza("Pepperoni"));
        pizzas.add(new BasicPizza("Ham"));

         for(Object bp : pizzas){
            System.out.println("Pizzas Name: "+ ((BasicPizza)bp).getName());
        }
        //start the sort
        Collections.sort(pizzas);
        //after sort
        System.out.println("ArrayList is sorted");
        for(Object bp : pizzas){
            System.out.println("Pizzas Name: "+ ((BasicPizza)bp).getName());
        }
    }
}





Printing items in inventory...

Inventory is empty at the moment.

Printing items in inventory...

Dough - 1.99 Quantity: 22 Value of Stock: $43.78
Sauce - 5.99 Quantity: 35 Value of Stock: $209.65
Cheese - 15.99 Quantity: 4 Value of Stock: $63.96
Pepperoni - 14.99 Quantity: 3 Value of Stock: $44.97
Ham - 16.99 Quantity: 2 Value of Stock: $33.98

Total value of inventory is: $396.34
BUILD SUCCESSFUL (total time: 0 seconds)

My previous post is only for example purposes! why do ur mixing?! -_-" I read your code, but i dont understand nothing!, try more!!! ;) lucky

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.