title: How to edit and add total sales value to txt file after purchase in JTable?
body: <p>I am creating an school project, an inventory program that lets the customer buy items from different products categories from the <code>JList</code>, that displays the items in a <code>JTable</code>, and then adds an item to the cart in another <code>JTable</code>.</p>
  
  <p>It has 2 main classes, <code>InventoryItems</code> and the <code>Inventory</code>. The interface below is a GUI class, but I will just provide the main code that edits/changes the text file.</p>
  
  <p>Here is a preview of the program:</p>
  
  <p><a href="https://i.stack.imgur.com/0EHk7.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/0EHk7.png" alt="enter image description here"></a></p>
  
  <p>The content of the txt file for category <code>Consoles</code>:</p>
  
  <pre><code> ID     Name      Price   Stocks  Items Sold  Total Sales
  00001 / Xbox 360 / 7999.0  / 20      /0          /0.0
  and so on....
  
      "/" is the line separator
  </code></pre>
  
  <p>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).</p>
  
  <p>Here is the full code for the database, under the class <code>InventoryItems</code>:</p>
  
  <pre><code>    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 -&gt; String.format(formatString, id);
              case 2 -&gt; String.format(formatString, id, itemName);
              case 3 -&gt; String.format(formatString, id, itemName, price);
              case 4 -&gt; String.format(formatString, id, itemName, price, quantity);
              case 5 -&gt; String.format(formatString, id, itemName, price, quantity, itemsSold);
              case 6 -&gt; String.format(formatString, id, itemName, price, quantity, itemsSold, totalSales);
              default -&gt; toString();
          };
      }
  }
  </code></pre>
  
  <p>Here is the code for editing the total sold item of an item upon purchase:</p>
  
  <pre><code>    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();
      }
  </code></pre>
  
  <p>Here is the code for editing the total sales of an item upon purchase:</p>
  
  <pre><code>  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();
          }
  </code></pre>
  
  <p>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.</p>
  
  <p>If a person buys and <code>Xbox 360</code> for <code>7999</code> the expected output would be:</p>
  
  <pre><code> ID      Name      Price   Stocks  Items Sold  Total Sales
  00001 / Xbox 360 / 7999.0   / 19      /1         /7999.0
  </code></pre>
  
  <p>If the person buys an <code>Xbox 360</code> again, it would be:</p>
  
  <pre><code>ID      Name      Price   Stocks  Items Sold  Total Sales
  00001 / Xbox 360 / 7999.0   / 18      /2         /15999.0
  </code></pre>
  
  <p>The full code for the Inventory class:</p>
  
  <pre><code>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&lt;InventoryItems&gt; items = new ArrayList&lt;&gt;();
      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 &lt; 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 &lt; 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+") &amp;&amp; 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 &gt; 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 &gt; 0) {
              format = formatString[0];
          }
          String[] itms = new String[items.size()];
          for (int i = 0; i &lt; 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 &gt;= 1) {
                      // Is it an actual integer value string
                      if (lineParts[0].matches("\\d+")) {
                          id = lineParts[0];
                      }
                      if (lineParts.length &gt;= 2) {
                          // Does the string contain a name or is it empty.
                          name = (lineParts[1].equals("") ? "Unknown" : lineParts[1]);
                          if (lineParts.length &gt;= 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 &gt;= 4) {
                                  // Is it an actual integer value string
                                  if (lineParts[0].matches("\\d+")) {
                                      quant = Integer.parseInt(lineParts[3]);
                                  }
                                  if (lineParts.length &gt;= 5) {
                                      // Is it an actual integer value string
                                      if (lineParts[0].matches("\\d+")) {
                                          sold = Integer.parseInt(lineParts[4]);
                                      }
                                      if (lineParts.length &gt;= 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 &amp; 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.&lt;br&gt;&lt;br&gt;
       *
       * @param inputString (String) The Unicode string to remove BOM's from.&lt;br&gt;
       *
       * @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;
      }
  
  }
  </code></pre>
  
  <p>Any idea or concept is welcome! and if you need more info about the code, I'll be glad to send it to you.</p>