0

I am creating an school project, an inventory program that lets the customer buy items from different products categories from the JList, that displays the items in a JTable, and then adds an item to the cart in another JTable.

It has 2 main classes, InventoryItems and the Inventory. The interface below is a GUI class, but I will just provide the main code that edits/changes the text file.

Here is a preview of the program:

enter image description here

The content of the txt file for category Consoles:

 ID     Name      Price   Stocks  Items Sold  Total Sales
00001 / Xbox 360 / 7999.0  / 20      /0          /0.0
and so on....

    "/" is the line separator

Someone helped me created a database to store the inventory items into the program that helps me edit and set values of the items like (item ID, item name, prices, stocks, items sold and total sales).

Here is the full code for the database, under the class InventoryItems:

    public class InventoryItems {

        private String id;
        private String itemName;
        private double price;
        private int quantity;
        private int itemsSold;
        private double totalSales;

        public InventoryItems() {    }

        public InventoryItems(String id, String itemName, double price, int quantity, int itemsSold, double totalSales) {
            this.id = id;
            this.itemName = itemName;
            this.price = price;
            this.quantity = quantity;
            this.itemsSold = itemsSold;
            this.totalSales = totalSales;
        }

        public String getId() {
            return id;
        }

        public void setId(String id) {
            this.id = id;
        }

        public String getItemName() {
            return itemName;
        }

        public void setItemName(String itemName) {
            this.itemName = itemName;
        }

        public double getPrice() { return price; }

        public void setPrice(double price) {
            this.price = price;
        }

        public int getQuantity() { return quantity; }

        public void setQuantity(int quantity) { this.quantity = quantity; }

        public int getItemsSold() {
            return itemsSold;
        }

        public void setItemsSold(int itemsSold) { this.itemsSold = itemsSold; }

        public double getTotalSales() {
            return totalSales;
        }

        public void setTotalSales(double totalSales) { this.totalSales = totalSales; }

@Override
    public String toString() {
        return new StringBuffer("").append("ID: ").append(id).append(", Item Name: ")
                .append(itemName).append(", Price: $").append(price)
                .append(", Quantity: ").append(quantity).append(", Items Sold: ").append(itemsSold)
        .append(", Total Sales: ").append(totalSales).toString();
    }

    /**
     * Returns instance data as a String in the format specified in your supplied
     * format string.
     *
     * @param formatString
     * @return
     */
    public String toString(String formatString) {
        if (formatString == null || formatString.equals("")) {
            return toString();
        }
        // String Format Specifiers must be separated
        // with a single white-space.
        return switch (formatString.split("\\s+").length) {
            case 1 -> String.format(formatString, id);
            case 2 -> String.format(formatString, id, itemName);
            case 3 -> String.format(formatString, id, itemName, price);
            case 4 -> String.format(formatString, id, itemName, price, quantity);
            case 5 -> String.format(formatString, id, itemName, price, quantity, itemsSold);
            case 6 -> String.format(formatString, id, itemName, price, quantity, itemsSold, totalSales);
            default -> toString();
        };
    }
}

Here is the code for editing the total sold item of an item upon purchase:

    public void setItemsSold(String idNumber, int newItemsSold) {
        if (!isInAdminMode) {
            System.err.println(ErrorMsg.NOT_ADMIN.msg);
            return;
        }
        if (items.isEmpty()) {
            System.err.println(ErrorMsg.LOAD_ERR.msg);
            return;
        }
        for (InventoryItems item : items) {
            if (item.getId().equals(idNumber)) {
                item.setItemsSold(newItemsSold); //I want this to increment an item value to 1 and so on as the user buys.
            }
        }
        refreshDataBase();
    }

Here is the code for editing the total sales of an item upon purchase:

  public void setTotalSales(String idNumber, new newTotalSales) {
            if (!isInAdminMode) {
                System.err.println(ErrorMsg.NOT_ADMIN.msg);
                return;
            }
            if (items.isEmpty()) {
                System.err.println(ErrorMsg.LOAD_ERR.msg);
                return;
            }
            for (InventoryItems item : items) {
                if (item.getId().equals(idNumber)) {
                    item.setQuantity(newTotalSales); //this only changes the value, not adding more to it.
                }
            }
            refreshDataBase();
        }

I'm just not sure on how to update the total sales repeatedly like it increases the value overtime. All it does is just set the total sales with the price of an item. It should add more value to the total sales, reduce the stocks and adding a value of an item sold.

If a person buys and Xbox 360 for 7999 the expected output would be:

 ID      Name      Price   Stocks  Items Sold  Total Sales
00001 / Xbox 360 / 7999.0   / 19      /1         /7999.0

If the person buys an Xbox 360 again, it would be:

ID      Name      Price   Stocks  Items Sold  Total Sales
00001 / Xbox 360 / 7999.0   / 18      /2         /15999.0

The full code for the Inventory class:

public class InventoryDemo extends JFrame {

    public enum ErrorMsg {
        LOAD_ERR("Inventory Items have not been loaded in yet!"),
        NOT_ADMIN("Invalid Operation! Admin Status Required!"),
        ID_EXISTS("Invalid ID! That ID Already Exists!"),
        NAME_EXISTS("Invalid Item Name! That Name Already Exists!");

        String msg;
        ErrorMsg(String msg) {
            this.msg = msg;
        }
        public String msg() {
            return msg;
        }
    }

    private static String encoding = "UTF-8"; // options: "US-ASCII", "UTF-8", "UTF-16"
    public static List<InventoryItems> items = new ArrayList<>();
    private boolean isInAdminMode = true;
    private static String dataFile = "Consoles.txt"; //name of txt file
    private String ls = System.lineSeparator();

    public static void main(String[] args) {
        new InventoryDemo().setVisible(true);
    }

    InventoryDemo() {
        if (!loadDataFile()) {
            System.err.println("Error Loading: " + dataFile);
            System.exit(0);
        }
        System.out.println("Items: " + list);
        System.out.println("Prices: " + list2);
        System.out.println(itemNameforInventoryDemo);
        System.out.println(itemPriceforInventoryDemo);

        }


    public boolean deleteInventoryItemID(String idToDelete) {
        if (!isInAdminMode) {
            System.err.println(ErrorMsg.NOT_ADMIN.msg);
            return false;
        }
        if (items.isEmpty()) {
            System.err.println(ErrorMsg.LOAD_ERR.msg);
            return false;
        }
        for (int i = 0; i < items.size(); i++) {
            if (items.get(i).getId().equals(idToDelete)) {
                items.remove(i);
                break;
            }
        }
        refreshDataBase();
        return true;
    }


    public boolean deleteInventoryItemName(String nameToDelete) {
        if (!isInAdminMode) {
            System.err.println(ErrorMsg.NOT_ADMIN.msg);
            return false;
        }
        if (items.isEmpty()) {
            System.err.println(ErrorMsg.LOAD_ERR.msg);
            return false;
        }
        for (int i = 0; i < items.size(); i++) {
            if (items.get(i).getItemName().equalsIgnoreCase(nameToDelete)) {
                items.remove(i);
                i--;
            }
        }
        refreshDataBase();
        return true;
    }


    public boolean addInventoryItem(String itemToAdd) {
        if (!isInAdminMode) {
            System.err.println(ErrorMsg.NOT_ADMIN.msg);
            return false;
        }
        try {
            String[] itemParts = itemToAdd.split("\\s{0,}/\\s{0,}");

            // Is Auto-ID-Increment required?
            if (!itemParts[0].matches("\\d+") && itemParts.length == 5){
                //Yes...
                String newID = getUniqueID();
                String[] parts = new String[6];
                parts[0] = newID;
                parts[1] = itemParts[0];
                parts[2] = itemParts[1];
                parts[3] = itemParts[2];
                parts[4] = itemParts[3];
                parts[5] = itemParts[4];
                itemParts = parts;
            }
            String id = itemParts[0];
            if (doesItemIDAlreadyExist(id)) {
                System.err.println("The Item ID (" + id + ") is an " + ErrorMsg.ID_EXISTS.msg);
                return false;
            }
            String name = itemParts[1];
            if (doesItemNameAlreadyExist(name)) {
                System.err.println("The Item Name (" + name + ") is an " + ErrorMsg.NAME_EXISTS.msg);
                return false;
            }
            double price = Double.parseDouble(itemParts[2]);
            int quant = Integer.parseInt(itemParts[3]);
            int sold = Integer.parseInt(itemParts[4]);
            double sales = Double.parseDouble(itemParts[5]);
            items.add(new InventoryItems(id, name, price, quant, sold, sales));
            refreshDataBase();
        }
        catch (Exception ex) {
            System.err.println(ex);
            return false;
        }
        return true;
    }

    public boolean doesItemIDAlreadyExist(String id) {
        boolean res = false;
        if (items.isEmpty()) {
            res = false;
        }
        else {
            for (InventoryItems itms : items) {
                if (itms.getId().equals(id)) {
                    res = true;
                    break;
                }
            }
        }
        return res;
    }

    public boolean doesItemNameAlreadyExist(String name) {
        boolean res = false;
        if (items.isEmpty()) {
            res = false;
        }
        else {
            for (InventoryItems itms : items) {
                if (itms.getItemName().equalsIgnoreCase(name)) {
                    res = true;
                    break;
                }
            }
        }
        return res;
    }

    public String getUniqueID() {
        if (items.isEmpty()) {
            return "00001";
        }
        int max = 0;
        for (InventoryItems itms : items) {
            String idVal = itms.getId();
            if (!idVal.matches("\\d+")) {
                continue;
            }
            int val = Integer.parseInt(idVal);
            if (val > max) {
                max = val;
            }
        }
        if (max == 0) {
            return String.format("%5s", 1).replace(' ', '0');
        }
        else {
            return String.format("%6s", (max + 1)).replace(' ', '0');
        }
    }

    public String[] getAllInventoryItems(String... formatString) {
        if (items.isEmpty()) {
            System.err.println(ErrorMsg.LOAD_ERR.msg);
            return null;
        }
        String format = "";
        if (formatString.length > 0) {
            format = formatString[0];
        }
        String[] itms = new String[items.size()];
        for (int i = 0; i < items.size(); i++) {
            if (!format.equals("")) {
                itms[i] = items.get(i).toString(format);
            }
            else {
                itms[i] = items.get(i).toString();
            }
        }
        return itms;
    }

    public String getItemID(String itemName) {
        if (items.isEmpty()) {
            System.err.println(ErrorMsg.LOAD_ERR.msg);
            return null;
        }
        String res = null;
        for (InventoryItems item : items) {
            if (item.getItemName().equalsIgnoreCase(itemName)) {
                res = item.getId();
                break;
            }
        }
        return res;
    }

    public void setItemID(String itemName, String newIDValue) {
        if (!isInAdminMode) {
            System.err.println(ErrorMsg.NOT_ADMIN.msg);
            return;
        }

        if (items.isEmpty()) {
            System.err.println(ErrorMsg.LOAD_ERR.msg);
            return;
        }
        for (InventoryItems item : items) {
            if (item.getItemName().equalsIgnoreCase(itemName)) {
                item.setId(newIDValue);
                break;
            }
        }
        refreshDataBase();
    }

    public String getItemString(String idNumber) {
        if (items.isEmpty()) {
            System.err.println(ErrorMsg.LOAD_ERR.msg);
            return null;
        }
        String res = null;
        for (InventoryItems item : items) {
            if (item.getId().equals(idNumber)) {
                res = item.toString();
                break;
            }
        }
        return res;
    }

    public String getItemName(String idNumber) {
        if (items.isEmpty()) {
            System.err.println(ErrorMsg.LOAD_ERR.msg);
            return null;
        }
        String res = null;
        for (InventoryItems item : items) {
            if (item.getId().equals(idNumber)) {
                res = item.getItemName();
                break;
            }
        }
        return res;
    }

    public void setItemName(String idNumber, String newName) {
        if (!isInAdminMode) {
            System.err.println(ErrorMsg.NOT_ADMIN.msg);
            return;
        }
        if (items.isEmpty()) {
            System.err.println(ErrorMsg.LOAD_ERR.msg);
            return;
        }
        for (InventoryItems item : items) {
            if (item.getId().equals(idNumber)) {
                item.setItemName(newName);
                break;
            }
        }
        refreshDataBase();
    }

    private double getItemPrice(String idNumber) {
        if (items.isEmpty()) {
            System.err.println(ErrorMsg.LOAD_ERR.msg);
            return 0.0d;
        }
        double res = 0.0d;
        for (InventoryItems item : items) {
            if (item.getId().equals(idNumber)) {
                res = item.getPrice();
                break;
            }
        }
        return res;
    }

    public void setItemPrice(String idNumber, double newPrice) {
        if (!isInAdminMode) {
            System.err.println(ErrorMsg.NOT_ADMIN.msg);
            return;
        }
        if (items.isEmpty()) {
            System.err.println(ErrorMsg.LOAD_ERR.msg);
            return;
        }
        for (InventoryItems item : items) {
            if (item.getId().equals(idNumber)) {
                item.setPrice(newPrice);
                break;
            }
        }
        refreshDataBase();
    }

    public int getItemQuantity(String idNumber) {
        if (items.isEmpty()) {
            System.err.println(ErrorMsg.LOAD_ERR.msg);
            return 0;
        }
        int res = 0;
        for (InventoryItems item : items) {
            if (item.getId().equals(idNumber)) {
                res = item.getQuantity();
                break;
            }
        }
        return res;
    }

    public void setItemQuantity(String idNumber, int newQuantity) {
        if (!isInAdminMode) {
            System.err.println(ErrorMsg.NOT_ADMIN.msg);
            return;
        }
        if (items.isEmpty()) {
            System.err.println(ErrorMsg.LOAD_ERR.msg);
            return;
        }
        for (InventoryItems item : items) {
            if (item.getId().equals(idNumber)) {
                item.setQuantity(newQuantity);
            }
        }
        refreshDataBase();
    }

    public int getItemsSold(String idNumber) {
        if (items.isEmpty()) {
            System.err.println(ErrorMsg.LOAD_ERR.msg);
            return 0;
        }
        int res = 0;
        for (InventoryItems item : items) {
            if (item.getId().equals(idNumber)) {
                res = item.getItemsSold();
                break;
            }
        }
        return res;
    }

    public void setItemsSold(String idNumber, int newItemsSold) {
        if (!isInAdminMode) {
            System.err.println(ErrorMsg.NOT_ADMIN.msg);
            return;
        }
        if (items.isEmpty()) {
            System.err.println(ErrorMsg.LOAD_ERR.msg);
            return;
        }
        for (InventoryItems item : items) {
            if (item.getId().equals(idNumber)) {
                item.setItemsSold(newItemsSold);
            }
        }
        refreshDataBase();
    }

    public double getTotalSales(String idNumber) {
        if (items.isEmpty()) {
            System.err.println(ErrorMsg.LOAD_ERR.msg);
            return 0;
        }
        double res = 0;
        for (InventoryItems item : items) {
          if (item.getId().equals(idNumber)) {
                res = item.getTotalSales();
                break;
            }
        }
        return res;
    }

    public void setTotalSales(String idNumber, new newTotalSales) {
        if (!isInAdminMode) {
            System.err.println(ErrorMsg.NOT_ADMIN.msg);
            return;
        }
        if (items.isEmpty()) {
            System.err.println(ErrorMsg.LOAD_ERR.msg);
            return;
        }
        for (InventoryItems item : items) {
            if (item.getId().equals(idNumber)) {
                item.setQuantity(newTotalSales);
            }
        }
        refreshDataBase();
    }

    public static boolean loadDataFile() {
        // See if the data file exists. If it doesn't then create it.
        // This will also create the the path to the file if it doesn't
        // already exist.
        if (!new File(dataFile).exists()) {
            createPathAndTextFile(dataFile);
            items.clear();  // Clear the Records Data List so to start fresh.
            return true; // Nothing in file at this point so, we exit method.
        }

        boolean success;
        items.clear();  // Clear the Records Data List.

        try (BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(dataFile), encoding))) {
            String line;
            while ((line = reader.readLine()) != null) {
                // Trim the data line and remove BOM's (if any).
                line = trimBOMs(line);
                // Skip the header line and blank lines (if any).
                if (line.equals("") || line.toLowerCase().startsWith("id")) {
                    continue;
                }
                String[] lineParts = line.split("\\s{0,}/\\s{0,}");
                // Validate record data types...
                String id = "";
                String name = "Unknown";
                double price = 0.0d;
                int quant = 0;
                int sold = 0;
                double sales = 0.0d;
                if (lineParts.length >= 1) {
                    // Is it an actual integer value string
                    if (lineParts[0].matches("\\d+")) {
                        id = lineParts[0];
                    }
                    if (lineParts.length >= 2) {
                        // Does the string contain a name or is it empty.
                        name = (lineParts[1].equals("") ? "Unknown" : lineParts[1]);
                        if (lineParts.length >= 3) {
                            // Is it an actual integer or double/float value string
                            if (lineParts[2].matches("-?\\d+(\\.\\d+)?")) {
                                price = Double.parseDouble(lineParts[2]);
                            }
                            if (lineParts.length >= 4) {
                                // Is it an actual integer value string
                                if (lineParts[0].matches("\\d+")) {
                                    quant = Integer.parseInt(lineParts[3]);
                                }
                                if (lineParts.length >= 5) {
                                    // Is it an actual integer value string
                                    if (lineParts[0].matches("\\d+")) {
                                        sold = Integer.parseInt(lineParts[4]);
                                    }
                                    if (lineParts.length >= 6) {
                                        // Is it an actual integer value string
                                        if (lineParts[0].matches("\\d+")) {
                                            sales = Double.parseDouble(lineParts[5]);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                items.add(new InventoryItems(id, name, price, quant, sold, sales));
            }
            success = true;
        }
        catch (FileNotFoundException ex) {
            System.err.println(ex);
            success = false;
        }
        catch (IOException ex) {
            System.err.println(ex);
            success = false;
        }
        return success;
    }

    public boolean saveItemsToFile() {
        if (!isInAdminMode) {
            System.err.println(ErrorMsg.NOT_ADMIN.msg);
            return false;
        }
        try (PrintWriter writer = new PrintWriter(new OutputStreamWriter(new FileOutputStream(dataFile), encoding))) {
            for (InventoryItems item : items) {
                String id = item.getId();
                String name = item.getItemName();
                double price = item.getPrice();
                int quant = item.getQuantity();
                int sold = item.getItemsSold();
                double sales = item.getTotalSales();
                String dataLine = String.format("%-6s/ %-25s/ %-8s/ %-4s /%-4s /%-4s%n", id, name, price, quant, sold, sales);
                writer.append(dataLine);
            }
            writer.flush();
        }
        catch (FileNotFoundException | UnsupportedEncodingException ex) {
            System.err.println(ex);
            return false;
        }
        return true;
    }

    public void refreshDataBase() {
        saveItemsToFile();
        loadDataFile();
    }


    public static boolean createPathAndTextFile(String pathString) {
        if (pathString.isEmpty()) {
            System.err.println("createPathAndTextFile() - Path & Text File Created: " + false);
            return false;
        }
        if (new File(pathString).exists()) {
            return true;
        }
        String pathToFile = new File(pathString).getAbsolutePath().substring(0, new File(pathString).getAbsolutePath().lastIndexOf(File.separator));
        String fileToCreate = new File(pathString).getAbsolutePath().substring(new File(pathString).getAbsolutePath().lastIndexOf(File.separator) + 1);

        try {
            //Make the directories path if it doesn't already exist...
            File dir = new File(pathToFile);
            if (!dir.exists()) {
                dir.mkdirs();
            }

            //Make the text file...
            File file = new File(dir, fileToCreate);
            FileWriter newFile = new FileWriter(file);
            newFile.close();
            if (new File(pathString).exists()) {
                return true;
            }
        }
        catch (IOException ex) {
            System.err.println("createPathAndTextFile() - Exception Encountered: "
                    + System.lineSeparator() + ex.getMessage());
        }
        return false;
    }

    public boolean isInAdminMode() {
        return isInAdminMode;
    }

    public void setIsInAdminMode(boolean isInAdminMode) {
        this.isInAdminMode = isInAdminMode;
    }

    public String getDataFilePath() {
        return dataFile;
    }

    public void setDataFilePath(String dataFile) {
        this.dataFile = dataFile;
    }

    public String getEncoding() {
        return encoding;
    }

    public void setEncoding(String encoding) {
        this.encoding = encoding;
    }

    /**
     * Removes (trims away) leading and trailing white-spaces and Removes
     * any BOM's (Byte Order Marks) from all the different Character Encodings.<br><br>
     *
     * @param inputString (String) The Unicode string to remove BOM's from.<br>
     *
     * @return (String)
     */
    private static String trimBOMs(String inputString) {
        inputString = inputString.trim()
                .replaceAll("\uFEFF|\uEFBBBF|\uFFFE|\u0000FEFF|\uFFFE0000|\u2B2F7638","")
                .replaceAll("\u2B2F7639|\u2B2F762B|\u2B2F762F|\u2B2F76382D|\uF7644C", "")
                .replaceAll("\uDD736673|\u0EFEFF|\uFBEE28|\u84319533", "");
        return inputString;
    }

}

Any idea or concept is welcome! and if you need more info about the code, I'll be glad to send it to you.

Andrew Thompson
  • 166,747
  • 40
  • 210
  • 420

0 Answers0