Results 1 to 13 of 13
Like Tree1Likes
  • 1 Post By Ronin

Thread: Finding it difficult to calculate total value and use currency format with GUI

  1. #1
    Ggrammer is offline Member
    Join Date
    Mar 2013
    Posts
    6
    Rep Power
    0

    Default Finding it difficult to calculate total value and use currency format with GUI

    I have been struggling with this last part to my inventory program. I am wondering if someone would be so kind as to help me understand why my calculations for the totalInventoryValue are not calculating properly and if there are any suggestions for improvement. Another problem I have run into is using the currency formatting after modifying my code to add a GUI. I know this may seem like a generic application but I am stumped even after reading the chapters in my textbook multiple times. Thank you to anyone that might lend a hand. I have included all three classes to my application in an attachment.
    Attached Files Attached Files

  2. #2
    Ronin is offline Senior Member
    Join Date
    Oct 2010
    Posts
    393
    Rep Power
    5

    Default Re: Finding it difficult to calculate total value and use currency format with GUI

    Hi Ggrammer, welcome to the forums.

    Can you please paste the code directly to your comments enclosing them in [code] tags.

    Regards.

  3. #3
    Ggrammer is offline Member
    Join Date
    Mar 2013
    Posts
    6
    Rep Power
    0

    Default No problem

    Yes that will be no problem. I am not quite sure how to use the [code] tags yet so I will try and hope that it works.


    Java Code:
    /** Program:  Inventory Program
     * File:      InventoryProgram.java
     * Summary:   The Inventory Program is a program that displays the inventory's product number,
     *            product name, number of units in stock, product price, and the value of the inventory.
     * Author:    
     * Date:      March 29, 2013
     **/
    
    import java.awt.GridLayout;       // required to create grid layout
    import java.awt.BorderLayout;     // required to create a border layout
    import java.awt.event.ActionEvent; // required for click events
    import java.awt.event.ActionListener; // required for click events
    import javax.swing.JPanel; // required to create panels
    import javax.swing.JFrame; // required to use the frame
    import javax.swing.JButton; // required to create buttons
    import javax.swing.JLabel; // required to create text fields
    import javax.swing.JTextField; // required to create text fields
    
    public class InventoryProgram extends JFrame implements ActionListener
    { // begin InventoryProgram class
       
       private JPanel gridPanel = new JPanel();
       private JPanel panel = new JPanel();
       
       JButton nextButton;
       
       JTextField itemNumberField;
       JTextField productNameField;
       JTextField numberOfUnitsInStockField;
       JTextField productPriceField;
       JTextField productInventoryValueField;
       JTextField brandNameField;
       JTextField restockFeeField;
       JTextField totalValueField;
       
       JLabel lblNumber;
       JLabel lblName;
       JLabel lblStock;
       JLabel lblPrice;
       JLabel lblInvValue;
       JLabel lblBrand;
       JLabel lblFee;
       JLabel lblTotValue;
       
       Product product1;
       Product product2;
       Product product3;
       Product product4;
       Product product5;
       
       private static final int MAX_PRODUCTS = 5;
       
       Product[] product = new Product[MAX_PRODUCTS];
       
       private static int ArrayIndex = 0;
       
       public InventoryProgram()
       {
         // instantiate Product class
          // creates instance of Product class and initializes class instance variables
          Product p1 = new Product("1Z279", "Stapler", 9, 4.39, "Boston");
          // creates instance of Product class and initializes class instance variables
          Product p2 = new Product("B329", "Box of Staples", 13, 3.99, "Swingline");
          // creates instance of Product class and initializes class instance variables
          Product p3 = new Product("103G", "Paper Clip", 1740, 0.02, "Revline");
          // creates instance of Product class and initializes class instance variables
          Product p4 = new Product("43IK", "Duster", 17, 3.89, "Clean Air");
          // creates instance of Product class and initializes class instance variables
          Product p5 = new Product("A749", "Mouse Pad", 21, 1.79, "Belkin");
         
          // add product objects to the array
          // adding Stapler product to the array of OfficeSupplies
          product[0] = p1;
          // adding Box of Staples product to the array of OfficeSupplies
          product[1] = p2;
          // adding Paper Clip product to the array of OfficeSupplies
          product[2] = p3;
          // adding Duster product to the array of OfficeSupplies
          product[3] = p4;
          // adding Mouse Pad product to the array of OfficeSupplies
          product[4] = p5;
          
          Product.sortByProductName(product); // sort the product oblects by name
          
          gridPanel.setLayout(new BorderLayout());
          gridPanel.add(this.createLabelPanel(), BorderLayout.WEST);
          gridPanel.add(this.createTextPanel(), BorderLayout.CENTER);
          gridPanel.add(this.createButtonPanel(), BorderLayout.SOUTH);
          
          add(gridPanel);
       
       }
       
       private JPanel createButtonPanel()
       {
          nextButton = new JButton("Display Product");
          nextButton.setActionCommand("Next");
          //nextButton.addActionListener(btnListen);
          nextButton.addActionListener(this);
          
          JPanel panel = new JPanel();
          panel.add(nextButton);
          
          return panel;
       }
       
       private JPanel createLabelPanel()
       {
          lblNumber = new JLabel("Product Number:");
          lblName = new JLabel("Product Name:");
          lblStock = new JLabel("Number of Units in Stock:");
          lblPrice = new JLabel("Product Price:");
          lblInvValue = new JLabel("Product Inventory Value:");
          lblBrand = new JLabel("Manufacturer:");
          lblFee = new JLabel("Restocking Fees:");
          lblTotValue = new JLabel("Total Inventory Value: ");
          
          panel = new JPanel();
          panel.setLayout(new GridLayout(8, 1));
          
          panel.add(lblNumber);
          panel.add(lblName);
          panel.add(lblStock);
          panel.add(lblPrice);
          panel.add(lblInvValue);
          panel.add(lblBrand);
          panel.add(lblFee);
          panel.add(lblTotValue);
          
          return panel;
       }
       
       private JPanel createTextPanel()
       {
          itemNumberField = new JTextField();
          itemNumberField.setEditable(false);
          
          productNameField = new JTextField();
          productNameField.setEditable(false);
          
          numberOfUnitsInStockField = new JTextField();
          numberOfUnitsInStockField.setEditable(false);
          
          productPriceField = new JTextField();
          productPriceField.setEditable(false);
          
          productInventoryValueField = new JTextField();
          productInventoryValueField.setEditable(false);
          
          brandNameField = new JTextField();
          brandNameField.setEditable(false);
          
          restockFeeField = new JTextField();
          restockFeeField.setEditable(false);
          
          totalValueField = new JTextField();
          totalValueField.setEditable(false);
          
          panel = new JPanel();
          panel.setLayout(new GridLayout(8, 1));
          
          panel.add(itemNumberField);
          panel.add(productNameField);
          panel.add(numberOfUnitsInStockField);
          panel.add(productPriceField);
          panel.add(productInventoryValueField);
          panel.add(brandNameField);
          panel.add(restockFeeField);
          panel.add(totalValueField);
          
          return panel;
       }
    
       public void actionPerformed(ActionEvent e)
       {
          if("Next".equals(e.getActionCommand()))
          {
             if(ArrayIndex < product.length)
             {
                itemNumberField.setText(product[ArrayIndex].getItemNumber());
                productNameField.setText(product[ArrayIndex].getProductName());
                numberOfUnitsInStockField.setText(String.valueOf(product[ArrayIndex].getNumberOfUnitsInStock()));
                productPriceField.setText(String.valueOf(product[ArrayIndex].getProductPrice()));
                productInventoryValueField.setText(String.valueOf(product[ArrayIndex].getProductInventoryValue()));
                brandNameField.setText(product[ArrayIndex].getBrandName());
                restockFeeField.setText(String.valueOf(product[ArrayIndex].calculateRestockFee()));
                product[ArrayIndex].totalInventoryValue(product[ArrayIndex].getProductInventoryValue());
                totalValueField.setText(String.valueOf(product[ArrayIndex].getTotalValue()));
                
                ArrayIndex = ArrayIndex + 1;
             }
          }
       }
       public static void main(String[] args)
       { // begin main method
          JFrame frame = new InventoryProgram(); // creat a frame object
          
          frame.setSize(300, 250);
          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          frame.setTitle("Office Supplies Inventory Program");
          frame.setLocationRelativeTo(null);
          frame.setVisible(true);
       } // end main method
    } // end InventoryProgram class




    Java Code:
    /** Program:  OfficeSupplies
     * File:      OfficeSupplies.java
     * Summary:   Sets, retrieves, and displays the inventory's product number, product name, number
     *            of units in stock, product price, and the value of the inventory.
     * Author:    
     * Date:      March 29, 2013
     **/
    
    import java.text.NumberFormat; // import Java package for currency format
    
    public class OfficeSupplies 
    { // begin OfficeSupplies class
       
       // declare instance variables
       // item number of the product
       private String itemNumber; 
       // name of the product
       private String productName; 
       // amount of the product in stock
       private int numberOfUnitsInStock; 
       // price of the product
       private double productPrice;
       // total value of inventory
       private static double totalValue;
       
       // used to format currency
       NumberFormat nf = NumberFormat.getCurrencyInstance();
       
       // declare empty OfficeSupplies contructors
       public OfficeSupplies() { }
       //  declare OfficeSupplies constructor with parameters
       public OfficeSupplies(String numberIn, String nameIn, int stockIn,
               double priceIn)
       { // begin OfficeSupplies constructor initializing class instanc variables
          
          // assign value numberIn to the itemNumber instance variable
          this.itemNumber = numberIn;
          // assign value nameIn to the productName instance variable
          this.productName = nameIn;
          // assign value stockIn to the numberOfUnitsInStock instance variable
          this.numberOfUnitsInStock = stockIn;
          // assign value priceIn to the productPrice instance variable
          this.productPrice = priceIn;
    
       } // end constructor
       
       public void setItemNumber(String numberIn)
       { // begin setItemNumber method
          /* set class instance variable itemNumber to value of parameter numberIn
           * that is passed in the method.
           */
          this.itemNumber = numberIn;
       } // end setItemNumber method
       
       public String getItemNumber()
       { // begin getItemNumber method
          // get value of class instance variable itemNumber
          return this.itemNumber;
       } // end getItemNumber method
       
       public void setProductName(String nameIn)
       { // begin setProductName method
          /* set class instance variable productName to value of parameter nameIn
           * that is passed in the method.
           */
          this.productName = nameIn;
       } // end setProductName method
       
       public String getProductName()
       { // begin getProductName method
          // get value of class instance variable productName
          return this.productName;
       } // end getProductName method
       
       public void setNumberOfUnitsInStock(int stockIn)
       { // begin setNumberOfUnitsInStock method
          /* set class instance variable numberOfUnitsInStock to value of parameter
           * stockIn that is passed in the method.
           */
          this.numberOfUnitsInStock = stockIn;
       } // end setNumberOfUnitsInStock method
       
       public int getNumberOfUnitsInStock()
       { // begin getNumberOfUnitsInStock method
          // get value of class instance variable numberOfUnitsInStock
          return numberOfUnitsInStock;
       } // end getNumberOfUnitsInStock method
       
       public void setProductPrice(double priceIn)
       { // begin setProductPrice method
          /* set class instance variable productPrice to value of parameter priceIn
           * that is passed in the method.
           */
          this.productPrice = priceIn;
       } // end setProductPrice method
       
       public double getProductPrice()
       { // begin getProductPrice method
          // get value of class instance variable producePrice
          return this.productPrice;
       } // end getProductPrice method
       
       public double getTotalValue()
       { // begin getTotalValue method
          /* get value of the sum of each officeSupplies 
           * object's productInventoryValue
          */
          return totalValue;
       } // end getTotalValue method
       
       /* calculates the inventory value by multiplying number of products in the
        * inventory with the price of the individual products
        */
       public double getProductInventoryValue() 
       { // begin productInventoryValue method
          // calculates the product of the numberOfUnitsInStock and productPrice
          return getNumberOfUnitsInStock() * getProductPrice();
       } // end productInventoryValue method
       
       public void totalInventoryValue(double inGetProductInventoryValue)
       { // begin totalInventoryValue method
          // sum of the total inventory's value
          totalValue = totalValue * inGetProductInventoryValue;
       } // end totalInventoryValue method
       
       public void displayOfficeSupplies()
       { // Begin displayOfficeSupplies method
          // displays office supplie's product number to the console
          System.out.println("Product Number: " + this.getItemNumber());
          // displays the office supplie's product name to the console
          System.out.println("Product Name: " + this.getProductName());
          // displays the office supplie's quantity in stock to the console
          System.out.println("Number of Units in Stock: "
                  + String.valueOf(this.getNumberOfUnitsInStock()));
          // displays the prices of the office suplies to the console
          System.out.println("Product Price: " + nf.format(getProductPrice()));
          // displays the total value of the office supplies in the the inventory
          System.out.println("Product Inventory Value: "
                  + nf.format(getProductInventoryValue()));
          // print blank line for readability
          System.out.println();
       } // end displayEmployeeWeeklyPay method
       
        public static void sortByProductName(OfficeSupplies[] officeSupplies)
        { // begin sortByProductName method
           // sorts the office supplies by name
           OfficeSupplies temp;
           for(int j=officeSupplies.length-2;j>=0;j--)
           { // begin for statement
             for(int n=0;n<=j;n++)
             { // begin for statement
                if(officeSupplies[n].getProductName().compareTo(officeSupplies[n+1]
                         .getProductName())>0)
                 { // begin if statement
                    temp=officeSupplies[n];
                    officeSupplies[n]=officeSupplies[n+1];
                    officeSupplies[n+1]=temp;
                 } // end if statement
             } // end for statement
           } // end for statement
        } // end sortByProductName method
    } // end OfficeSupplies class





    Java Code:
    /** Program:  Product
     * File:      Product.java
     * Summary:   Inherits all properties and methods of the OfficeSupplies class while the Manufacturer
     *            subclass contains its own methods to set, retrieve, and display the manufacturer's
     *            brand name of each product.
     * Author:    
     * Date:      March 29, 2013
     **/
    
    public class Product extends OfficeSupplies
    { // begin Product class
       
       // declare instance variables
       private String brandName; // the products' brand names
       private final double restockFee = 0.05; // used to compute 5% restocking fee
       
       public Product() {} // empty constructor
       // constructor to initialize class instance variables
       public Product(String numberIn, String nameIn, int stockIn, double priceIn, String brandNameIn)
       { 
          // call superclass constructor
          super(numberIn, nameIn, stockIn, priceIn);
          // set the brand name
          this.brandName = brandNameIn;
       }
       
       public void setBrandName(String brandNameIn)
       { // begin setBrandName method
          // set the product's brand name
          this.brandName = brandNameIn;
       } // end setBrandName method
       
       public String getBrandName()
       { // begin getBrandName method
          // get the product's brand name
          return brandName;
       } // end getBrandName method
       
       public double calculateRestockFee()
       { // begin calculateRestockFee method
          // calculates the inventory's restocking costs
          return (restockFee * getProductInventoryValue());
       } // end calculateRestockFee method
       
       @Override
       
       public void displayOfficeSupplies()
       { // override the displayOfficeSupplies method in the OfficeSupplies class
          // displays office supplie's product number to the console
          System.out.println("Product Number: " + this.getItemNumber());
          // displays the office supplie's product name to the console
          System.out.println("Product Name: " + this.getProductName());
          // displays the office supplie's quantity in stock to the console
          System.out.println("Number of Units in Stock: "
                  + String.valueOf(this.getNumberOfUnitsInStock()));
          // displays the prices of the office suplies to the console
          System.out.println("Product Price: " + nf.format(getProductPrice()));
          // displays the total value of the office supplies in the the inventory
          System.out.println("Product Inventory Value: "
                  + nf.format(getProductInventoryValue()));
          // displays the brand name of the product to the console
          System.out.println("Manufacturer: " + String.valueOf(this.getBrandName()));
          // displays the restocking fees for each product inventory
          System.out.println("Restocking Fees: " + nf.format(calculateRestockFee()));
       } // end displayOfficeSupplies method
    } // end Product class
    Last edited by Ggrammer; 03-30-2013 at 03:20 AM.

  4. #4
    pbrockway2 is offline Moderator
    Join Date
    Feb 2009
    Location
    New Zealand
    Posts
    4,585
    Rep Power
    12

    Default Re: Finding it difficult to calculate total value and use currency format with GUI

    Another problem I have run into is using the currency formatting after modifying my code to add a GUI.
    In the displayOfficeSupplies() method - both versions - you use a NumberFormat instance to ensure that money values are printed nicely. You have to do the same thing whenever you set the text of components that are intended to display money values which you do in the actionPerformed() method:

    Java Code:
    productPriceField.setText(String.valueOf(product[ArrayIndex].getProductPrice()));
    getProductPrice() returns a double. You should use a NumberFormat instance to get a nice looking String from the double, and not String.valueOf().

  5. #5
    pbrockway2 is offline Moderator
    Join Date
    Feb 2009
    Location
    New Zealand
    Posts
    4,585
    Rep Power
    12

    Default Re: No problem

    I am wondering if someone would be so kind as to help me understand why my calculations for the totalInventoryValue are not calculating properly
    In actionPerformed() you say

    Java Code:
    product[ArrayIndex].totalInventoryValue(product[ArrayIndex].getProductInventoryValue());
    You call totalInventoryValue() which returns you the - correctly calculated - total inventory value, but then you do nothing at all with the double value it returns. What you should do is use it in a call to setText() of the appropriate text field. (nicely formatted, of course.)

    ---

    Welcome to the forums! And thanks for the code tags.

    Another thing that can really help people to help you is to describe a problem as fully as you can: so instead of the calculations not "calculating properly", say what you expected to see (what value in which text field when "next" is clicked) and what you did see (I'm guessing no change in what the text field displayed). I completely realise how difficult such long winded objectivity can be when you're stumped/frustrated/and still trying to figure things out. But most of us have learnt (painfully) that it's the only way to begin diagnosing the cause of a problem.

    Again, welcome.

  6. #6
    Ggrammer is offline Member
    Join Date
    Mar 2013
    Posts
    6
    Rep Power
    0

    Default Re: Finding it difficult to calculate total value and use currency format with GUI

    Quote Originally Posted by pbrockway2 View Post
    In the displayOfficeSupplies() method - both versions - you use a NumberFormat instance to ensure that money values are printed nicely. You have to do the same thing whenever you set the text of components that are intended to display money values which you do in the actionPerformed() method:

    Java Code:
    productPriceField.setText(String.valueOf(product[ArrayIndex].getProductPrice()));
    getProductPrice() returns a double. You should use a NumberFormat instance to get a nice looking String from the double, and not String.valueOf().
    Hello pbrockway2,

    Thank you so much for your help. I have looked over this code through-and-through but still seemed to overlook this issue. I have applied the NumberFormat to the GUI and the output is exactly what I needed it to display as far as the formatting in the value TextFields.

  7. #7
    Ggrammer is offline Member
    Join Date
    Mar 2013
    Posts
    6
    Rep Power
    0

    Default Re: No problem

    Quote Originally Posted by pbrockway2 View Post
    In actionPerformed() you say

    Java Code:
    product[ArrayIndex].totalInventoryValue(product[ArrayIndex].getProductInventoryValue());
    You call totalInventoryValue() which returns you the - correctly calculated - total inventory value, but then you do nothing at all with the double value it returns. What you should do is use it in a call to setText() of the appropriate text field. (nicely formatted, of course.)

    ---

    Welcome to the forums! And thanks for the code tags.

    Another thing that can really help people to help you is to describe a problem as fully as you can: so instead of the calculations not "calculating properly", say what you expected to see (what value in which text field when "next" is clicked) and what you did see (I'm guessing no change in what the text field displayed). I completely realise how difficult such long winded objectivity can be when you're stumped/frustrated/and still trying to figure things out. But most of us have learnt (painfully) that it's the only way to begin diagnosing the cause of a problem.

    Again, welcome.
    Hello pbrockway2,

    Again I really appreciate your interest in lending me your time while reviewing my code. I understand your suggestions about fully clarifying my problem. Here is my problem with the calculations in my code. I am trying to output the total value of all five array objects but I am having difficulty figuring out the correct formula for the totalInventoryValue method.

    In the OfficeSupplies class:
    Java Code:
       // total value of inventory
       private static double totalValue;
    
       public double getTotalValue()
       { // begin getTotalValue method
          /* get value of the sum of each officeSupplies 
           * object's productInventoryValue
          */
          return totalValue;
       } // end getTotalValue method
    
       public void totalInventoryValue(double inGetProductInventoryValue)
       { // begin totalInventoryValue method
          // sum of the total inventory's value
          totalValue = totalValue * inGetProductInventoryValue;
       } // end totalInventoryValue method

  8. #8
    pbrockway2 is offline Moderator
    Join Date
    Feb 2009
    Location
    New Zealand
    Posts
    4,585
    Rep Power
    12

    Default Re: Finding it difficult to calculate total value and use currency format with GUI

    I am trying to output the total value of all five array objects but I am having difficulty figuring out the correct formula for the totalInventoryValue method.
    Why not call getProductInventoryValue() for each of the five items and add together what they return to get the total? That way makes more sense than having a totalInventoryValue() method in the OfficeSupplies class. (In real life office supplies do not know anything about how many of other office supplies there might be in stock. The simplest approach is to model the OfficeSupplies class on this reality.)

  9. #9
    Ronin is offline Senior Member
    Join Date
    Oct 2010
    Posts
    393
    Rep Power
    5

    Default Re: Finding it difficult to calculate total value and use currency format with GUI

    Hi Ggrammer,

    I think you may be getting slightly lost in what you want your program to do but correct me if I am wrong.

    To report on the total value of the products the OfficeSupplies class would need to know about the Products. To do this it would need to know about the Product array which would suggest the Product array should be held here and created from data passed in from the GUI. Product itself does not need to extend OfficeSupplies.

    As a general rule of thumb I try to ensure most of the functionality is done outside of the GUI. The GUI is just there to provide a fancy view of the data and functionality performed by a console application.

    EDIT: 15 minutes after the last post! I need to learn to type faster.

    Regards.

  10. #10
    Ggrammer is offline Member
    Join Date
    Mar 2013
    Posts
    6
    Rep Power
    0

    Default Re: Finding it difficult to calculate total value and use currency format with GUI

    Hello Ronin,

    I appreciate your help so far. I am grateful for you time and effort. I think I may have found the solution except for one error that I am now receiving in the InventoryProgram.

    Java Code:
    /** Program:  Inventory Program
     * File:      InventoryProgram.java
     * Summary:   The Inventory Program is a program that displays the inventory's product number,
     *            product name, number of units in stock, product price, and the value of the inventory.
     * Author:    Ggrammer
     * Date:      April 14, 2013
     **/
    
    import java.text.NumberFormat; // import Java package for currency format
    
    import java.awt.GridLayout; // used to create grid layout
    import java.awt.BorderLayout; // used to create border layout
    import java.awt.event.ActionEvent; // used for click events
    import java.awt.event.ActionListener; // used for click events
    import javax.swing.JPanel; // used to create panels
    import javax.swing.JFrame; // used to use the frame
    import javax.swing.JButton; // used to create buttons
    import javax.swing.JLabel; // used to create text fields
    import javax.swing.JTextField; // used to create text fields
    import javax.swing.ImageIcon; // used to access images
    
    public class InventoryProgram extends JFrame implements ActionListener
    { // begin InventoryProgram class
       
       // used to format currency
       NumberFormat nf = NumberFormat.getCurrencyInstance();
       
       // Declare panels
       private JPanel gridPanel = new JPanel(); // panel that contains gridlayout
       private JPanel panel = new JPanel(); // panel to contain buttons, lables and text fields
       
       // declare buttons
       JButton firstButton; // button to view the first array item
       JButton previousButton; // button to view the previous array item
       JButton nextButton; // button to view the next array item
       JButton lastButton; // button to view the last array item
       
       // declare text fields
       JTextField itemNumberField; // field with the product number
       JTextField productNameField; // field with the product name
       JTextField numberOfUnitsInStockField; // field with the number of units in stock
       JTextField productPriceField; // field with the price of the product
       JTextField productInventoryValueField; // field with the value of the product's inventory
       JTextField brandNameField; // field with the brand name
       JTextField restockFeeField; // field containing the product's restock fees
       JTextField totalValueField; // field containg the entire inventory value
       
       // declare labels
       JLabel lblNumber; // product number label 
       JLabel lblName; // product name label
       JLabel lblStock; // number of units in stock label
       JLabel lblPrice; // product price label
       JLabel lblInvValue; // product inventory value label
       JLabel lblBrand; // brand name label
       JLabel lblFee; // restocking fees label
       JLabel lblTotValue; // total value label
       
       // declaring 5 product objects
       DeskItem product1;
       DeskItem product2;
       DeskItem product3;
       DeskItem product4;
       DeskItem product5;
       
       private static final int MAX_DESKITEMS = 5; // set maximum size for DeskItem Array
       
       DeskItem[] deskItem = new DeskItem[MAX_DESKITEMS]; // create DeskItem Array object
       
       private static int ArrayIndex = 0; // array index
       
       public InventoryProgram() // constructor
       {
         // initialize 5 DeskItem objects
          // creates instance of DeskItem class and initializes class instance variables
          DeskItem deskItem1 = new DeskItem("1Z279", "Stapler", 9, 4.39, "Boston");
          // creates instance of DeskItem class and initializes class instance variables
          DeskItem deskItem2 = new DeskItem("B329", "Box of Staples", 13, 3.99, "Swingline");
          // creates instance of DeskItem class and initializes class instance variables
          DeskItem deskItem3 = new DeskItem("103G", "Paper Clip", 1740, 0.02, "Revline");
          // creates instance of DeskItem class and initializes class instance variables
          DeskItem deskItem4 = new DeskItem("43IK", "Duster", 17, 3.89, "Clean Air");
          // creates instance of DeskItem class and initializes class instance variables
          DeskItem deskItem5 = new DeskItem("A749", "Mouse Pad", 21, 1.79, "Belkin");
         
          // add product objects to the array
          // adding Stapler product to the array of OfficeSupplies
          deskItem[0] = deskItem1;
          // adding Box of Staples product to the array of OfficeSupplies
          deskItem[1] = deskItem2;
          // adding Paper Clip product to the array of OfficeSupplies
          deskItem[2] = deskItem3;
          // adding Duster product to the array of OfficeSupplies
          deskItem[3] = deskItem4;
          // adding Mouse Pad product to the array of OfficeSupplies
          deskItem[4] = deskItem5;
          
          DeskItem.sortByProductName(deskItem); // sort the product oblects by name
          
          gridPanel.setLayout(new BorderLayout()); // creates border layout
          gridPanel.add(this.createLabelPanel(), BorderLayout.WEST); // adds label panel
          gridPanel.add(this.createTextPanel(), BorderLayout.CENTER); // adds field panel
          gridPanel.add(this.createButtonPanel(), BorderLayout.SOUTH); // adds button panel
          add(gridPanel);
       }
       
       private JPanel createButtonPanel()
       {      
          // create button objects
          firstButton = new JButton("First"); // creates and labels button first
          firstButton.setActionCommand("First"); // action command for button click event
          firstButton.addActionListener(this); // adds Listener command to firstButton
          
          previousButton = new JButton("Previous"); // creates and labels button previous
          previousButton.setActionCommand("Previous"); // action command for button click event
          previousButton.addActionListener(this); // adds Listener command to previousButton
          
          nextButton = new JButton("Next"); // creates and labels button next
          nextButton.setActionCommand("Next"); // action command for button click event
          nextButton.addActionListener(this); // adds Listener command to nextButton
          
          lastButton = new JButton("Last"); // creates and labels button last
          lastButton.setActionCommand("Last"); // action comand for button click event
          lastButton.addActionListener(this); // adds Lestener command to nextButton
          
          //creates panel object
          JPanel panel = new JPanel();
          
          panel.add(firstButton); // adds the first button
          panel.add(previousButton); // adds the previous button
          panel.add(nextButton); // adds the next button
          panel.add(lastButton); // adds the last button
          
          return panel; // returns panel
       } // end creatButtonPanel method
       
       private JPanel createLabelPanel()
       {
          // create instances of label objects
          ImageIcon icon = new ImageIcon(".\\SRC\\pencilLogo.gif");
          JLabel lblLogo = new JLabel(icon);
          lblNumber = new JLabel("Product Number:"); // label for product number
          lblName = new JLabel("Product Name:"); // label for product name
          lblStock = new JLabel("Number of Units in Stock:"); // label for number of units in stock
          lblPrice = new JLabel("Product Price:"); // label for product price
          lblInvValue = new JLabel("Product Inventory Value:"); // label for product inventory value
          lblBrand = new JLabel("Manufacturer:"); // label for the brand names
          lblFee = new JLabel("Restocking Fees:"); // label for restocking fees
          lblTotValue = new JLabel("Total Inventory Value: "); // label for the total inventory value
          
          panel = new JPanel();
          panel.setLayout(new GridLayout(9, 1));
          
          // adds labels to the panel
          panel.add(lblLogo);
          panel.add(lblNumber);
          panel.add(lblName);
          panel.add(lblStock);
          panel.add(lblPrice);
          panel.add(lblInvValue);
          panel.add(lblBrand);
          panel.add(lblFee);
          panel.add(lblTotValue);
          
          return panel; // returns panel
       } // end creatLabelPanel method
       
       private JPanel createTextPanel()
       {
          // creates instances of text boxes
          JLabel lblCompanyName = new JLabel("    Zoor Office Place"); // company name label
          
          itemNumberField = new JTextField(); // text field for the product number
          itemNumberField.setEditable(false); // sets field as uneditable for the user
          
          productNameField = new JTextField(); // text field for the product name
          productNameField.setEditable(false); // sets field as uneditable for the user
          
          numberOfUnitsInStockField = new JTextField(); // text field for the number of units in stock
          numberOfUnitsInStockField.setEditable(false); // sets field as uneditable for the user
          
          productPriceField = new JTextField(); // text field for the product price
          productPriceField.setEditable(false); // set the field as uneditable for the user
          
          productInventoryValueField = new JTextField(); // text field for the inventory value
          productInventoryValueField.setEditable(false); // sets the field as uneditable for the user
          
          brandNameField = new JTextField(); // text field for the brand name
          brandNameField.setEditable(false); // sets the field as uneditable for the user
          
          restockFeeField = new JTextField(); // text field for the restocking fee
          restockFeeField.setEditable(false); // sets the field as uneditable for the user
          
          totalValueField = new JTextField(); // text field for the total value
          totalValueField.setEditable(false); // sets the field as uneditable for the user
          
          panel = new JPanel(); // creates panel object
          panel.setLayout(new GridLayout(9, 1)); // creates a grid layout for the fields
          
          panel.add(lblCompanyName); // company name and logo field
          panel.add(itemNumberField); // adds the product number field to grid layout
          panel.add(productNameField); // adds the product name field to grid layout
          panel.add(numberOfUnitsInStockField); // adds the number of units in stock field to grid layout
          panel.add(productPriceField); // adds the product price field to grid layout
          panel.add(productInventoryValueField); // adds product inventory value field to grid layout
          panel.add(brandNameField); // adds brand name field to grid layout
          panel.add(restockFeeField); // adds restocking fee field to grid layout
          panel.add(totalValueField); // adds total value field to grid layout
          
          return panel; // returns panel
       } // end createTextPanel method
    
       @Override
       public void actionPerformed(ActionEvent e)
       {
          if(deskItem[ArrayIndex].getTotalValue()==0)
          {
             for(int x=0;x<deskItem.length;x++)
                deskItem[x].totalInventoryValue(deskItem[x].getProductInventoryValue());
          }
          
             totalValueField.setText(nf.format(deskItem[ArrayIndex].getTotalValue()));
                     
          // add button functions
          if("First".equals(e.getActionCommand())) // if First button
          {
             ArrayIndex = 0;
             setFieldValues();
          } // end if
          
          if("Previous".equals(e.getActionCommand()))
          {
             if(ArrayIndex == 0)
             {
                ArrayIndex = deskItem.length - 1;
                setFieldValues();
             }
             
             else
             {
                ArrayIndex--;
                setFieldValues();
             }
          }
          
          
          if("Next".equals(e.getActionCommand()))
          {
             if(ArrayIndex == deskItem.length - 1)
             {
                ArrayIndex = 0;
                setFieldValues();
             }
             
             else
             {
                ArrayIndex++;
                setFieldValues();
             }
          }
          
          if("Last".equals(e.getActionCommand()))
          {
             ArrayIndex = deskItem.length - 1;
             setFieldValues();
          }
       } // end actionPerformed
       
       private void setFieldValues()
          {
             itemNumberField.setText(deskItem[ArrayIndex].getItemNumber()); // gets the product number
             productNameField.setText(deskItem[ArrayIndex].getProductName()); // gets the product name
             // gets the number of units in stock
             numberOfUnitsInStockField.setText(String.valueOf(deskItem[ArrayIndex].getNumberOfUnitsInStock()));
             // gets the product price 
             productPriceField.setText(nf.format(deskItem[ArrayIndex].getProductPrice()));
             // gets the product inventory value
             productInventoryValueField.setText(nf.format(deskItem[ArrayIndex].getProductInventoryValue()));
             // gets the brand name
             brandNameField.setText(deskItem[ArrayIndex].getBrandName());
             // gets the restocking fee
             restockFeeField.setText(nf.format(deskItem[ArrayIndex].calculateRestockFee()));
             // computes the total value of the inventory
             deskItem[ArrayIndex].totalInventoryValue(deskItem[ArrayIndex].getProductInventoryValue());
             // gets the total inventory value
             totalValueField.setText(nf.format(deskItem[ArrayIndex].getTotalValue()));
          }
       
       public static void main(String[] args)
       { // begin main method
          JFrame frame = new InventoryProgram(); // creat a frame object
          
          frame.setSize(400, 350); // sets the size of the window with a width of 300 and height of 250
          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // closes application
          frame.setTitle("Office Supplies Inventory Program"); // sets the title of the window
          frame.setLocationRelativeTo(null); // center the form
          frame.setVisible(true); // displays the form
       } // end main method
    } // end InventoryProgram class

    Java Code:
    /** Program:  OfficeSupplies
     * File:      OfficeSupplies.java
     * Summary:   Sets, retrieves, and displays the inventory's product number, product name, number
     *            of units in stock, product price, and the value of the inventory.
     * Author:    Ggrammer
     * Date:      April 14, 2013
     **/
    
    import java.text.NumberFormat; // import Java package for currency format
    
    public class OfficeSupplies 
    { // begin OfficeSupplies class
       
       // declare instance variables
       // item number of the product
       private String itemNumber; 
       // name of the product
       private String productName; 
       // amount of the product in stock
       private int numberOfUnitsInStock; 
       // price of the product
       private double productPrice;
       //
       private static double productInventoryValue;
       // total value of inventory
       private static double totalValue = 0;
       
       // used to format currency
       NumberFormat nf = NumberFormat.getCurrencyInstance();
       
       // declare empty OfficeSupplies contructors
       public OfficeSupplies() { }
       //  declare OfficeSupplies constructor with parameters
       public OfficeSupplies(String numberIn, String nameIn, int stockIn,
               double priceIn)
       { // begin OfficeSupplies constructor initializing class instanc variables
          // assign value numberIn to the itemNumber instance variable
          this.itemNumber = numberIn;
          // assign value nameIn to the productName instance variable
          this.productName = nameIn;
          // assign value stockIn to the numberOfUnitsInStock instance variable
          this.numberOfUnitsInStock = stockIn;
          // assign value priceIn to the productPrice instance variable
          this.productPrice = priceIn;
       } // end constructor
       
       public void setItemNumber(String numberIn)
       { // begin setItemNumber method
          /* set class instance variable itemNumber to value of parameter numberIn
           * that is passed in the method.
           */
          this.itemNumber = numberIn;
       } // end setItemNumber method
       
       public String getItemNumber()
       { // begin getItemNumber method
          // get value of class instance variable itemNumber
          return this.itemNumber;
       } // end getItemNumber method
       
       public void setProductName(String nameIn)
       { // begin setProductName method
          /* set class instance variable productName to value of parameter nameIn
           * that is passed in the method.
           */
          this.productName = nameIn;
       } // end setProductName method
       
       public String getProductName()
       { // begin getProductName method
          // get value of class instance variable productName
          return this.productName;
       } // end getProductName method
       
       public void setNumberOfUnitsInStock(int stockIn)
       { // begin setNumberOfUnitsInStock method
          /* set class instance variable numberOfUnitsInStock to value of parameter
           * stockIn that is passed in the method.
           */
          this.numberOfUnitsInStock = stockIn;
       } // end setNumberOfUnitsInStock method
       
       public int getNumberOfUnitsInStock()
       { // begin getNumberOfUnitsInStock method
          // get value of class instance variable numberOfUnitsInStock
          return numberOfUnitsInStock;
       } // end getNumberOfUnitsInStock method
       
       public void setProductPrice(double priceIn)
       { // begin setProductPrice method
          /* set class instance variable productPrice to value of parameter priceIn
           * that is passed in the method.
           */
          this.productPrice = priceIn;
       } // end setProductPrice method
       
       public double getProductPrice()
       { // begin getProductPrice method
          // get value of class instance variable producePrice
          return this.productPrice;
       } // end getProductPrice method
       
       public double getProductInventoryValue()
       {
          return this.productInventoryValue;
       }
       
       /* calculates the inventory value by multiplying number of products in the
        * inventory with the price of the individual products
        */
       public void calculateProductInventoryValue() 
       { // begin productInventoryValue method
          // calculates the product of the numberOfUnitsInStock and productPrice
          productInventoryValue = numberOfUnitsInStock * productPrice;
       } // end productInventoryValue method
       
       public double getTotalValue()
       { // begin getTotalValue method
          /* get value of the sum of each officeSupplies 
           * object's productInventoryValue
          */
          return totalValue;
       } // end getTotalValue method
       
       public void totalInventoryValue()
       { // begin totalInventoryValue method
          // sum of the total inventory's value
          totalValue = totalValue + getProductInventoryValue();
       } // end totalInventoryValue method
       
       public void displayOfficeSupplies()
       { // Begin displayOfficeSupplies method
          // displays office supplie's product number to the console
          System.out.println("Product Number: " + this.getItemNumber());
          // displays the office supplie's product name to the console
          System.out.println("Product Name: " + this.getProductName());
          // displays the office supplie's quantity in stock to the console
          System.out.println("Number of Units in Stock: "
                  + String.valueOf(this.getNumberOfUnitsInStock()));
          // displays the prices of the office suplies to the console
          System.out.println("Product Price: " + nf.format(getProductPrice()));
          // displays the total value of the office supplies in the the inventory
          System.out.println("Product Inventory Value: "
                  + nf.format(getProductInventoryValue()));
          // print blank line for readability
          System.out.println();
       } // end displayEmployeeWeeklyPay method
       
        public static void sortByProductName(OfficeSupplies[] officeSupplies)
        { // begin sortByProductName method
           // sorts the office supplies by name
           OfficeSupplies temp;
           for(int j=officeSupplies.length-2;j>=0;j--)
           { // begin for statement
             for(int n=0;n<=j;n++)
             { // begin for statement
                if(officeSupplies[n].getProductName().compareTo(officeSupplies[n+1]
                         .getProductName())>0)
                 { // begin if statement
                    temp=officeSupplies[n];
                    officeSupplies[n]=officeSupplies[n+1];
                    officeSupplies[n+1]=temp;
                 } // end if statement
             } // end for statement
           } // end for statement
        } // end sortByProductName method
    } // end OfficeSupplies class


    Java Code:
    /** Program:  DeskItem
     * File:      DeskItem.java
     * Summary:   Inherits all properties and methods of the OfficeSupplies class while the DeskItem
     *            subclass contains its own methods to set, retrieve, and display the manufacturer's
     *            brand name of each product.
     * Author:    Greg DiLernia
     * Date:      March 24, 2013
     **/
    
    public class DeskItem extends OfficeSupplies
    { // begin DeskItem class
       
       // declare instance variables
       private String brandName; // the products' brand names
       private final double restockFee = 0.05; // used to compute 5% restocking fee
       private static double totalValue;
       
       public DeskItem() {} // empty constructor
       // constructor to initialize class instance variables
       public DeskItem(String numberIn, String nameIn, int stockIn, double priceIn, String brandNameIn)
       { 
          // call superclass constructor
          super(numberIn, nameIn, stockIn, priceIn);
          // set the brand name
          this.brandName = brandNameIn;
       }
       
       public void setBrandName(String brandNameIn)
       { // begin setBrandName method
          // set the product's brand name
          this.brandName = brandNameIn;
       } // end setBrandName method
       
       public String getBrandName()
       { // begin getBrandName method
          // get the product's brand name
          return brandName;
       } // end getBrandName method
       
       public double calculateRestockFee()
       { // begin calculateRestockFee method
          // calculates the inventory's restocking costs
          return (restockFee * getProductInventoryValue());
       } // end calculateRestockFee method
       
       @Override
       public double getTotalValue()
       { // begin getTotalValue method
          /* get value of the sum of each officeSupplies 
           * object's productInventoryValue
          */
          return totalValue;
       } // end getTotalValue method
       
       @Override
       public void totalInventoryValue()
       { // begin totalInventoryValue method
          // sum of the total inventory's value
          totalValue = totalValue + getProductInventoryValue();
       } // end totalInventoryValue method
       
       @Override
       
       public void displayOfficeSupplies()
       { // override the displayOfficeSupplies method in the OfficeSupplies class
          // displays office supplie's product number to the console
          System.out.println("Product Number: " + this.getItemNumber());
          // displays the office supplie's product name to the console
          System.out.println("Product Name: " + this.getProductName());
          // displays the office supplie's quantity in stock to the console
          System.out.println("Number of Units in Stock: "+ String.valueOf(this.getNumberOfUnitsInStock()));
          // displays the prices of the office suplies to the console
          System.out.println("Product Price: " + nf.format(getProductPrice()));
          // displays the total value of the office supplies in the the inventory
          System.out.println("Product Inventory Value: "+ nf.format(getProductInventoryValue()));
          // displays the brand name of the product to the console
          System.out.println("Manufacturer: " + String.valueOf(this.getBrandName()));
          // displays the restocking fees for each product inventory
          System.out.println("Restocking Fees: " + nf.format(calculateRestockFee()));
       } // end displayOfficeSupplies method
    } // end DeskItem class

    I have gotten the an error stating:
    "no suitable method found for totalInventoryValue(double)
    method DeskItem.totalInventoryValue() is not applicable (actual and formal argument lists differ in length)"


    InventoryProgram: Line 218
    Java Code:
    deskItem[x].totalInventoryValue(deskItem[x].getProductInventoryValue());
    I have also received an error:
    "no suitable method found for totalInventoryValue(double)
    method DeskItem.totalInventoryValue() is not applicable
    (actual and formal argument lists differ in length)"

    for this line of code.


    InventoryProgram: Line 283
    Java Code:
    deskItem[ArrayIndex].totalInventoryValue(deskItem[ArrayIndex].getProductInventoryValue());
    Last edited by Ggrammer; 04-15-2013 at 01:42 AM.

  11. #11
    Ronin is offline Senior Member
    Join Date
    Oct 2010
    Posts
    393
    Rep Power
    5

    Default Re: Finding it difficult to calculate total value and use currency format with GUI

    Hi Ggrammer,

    The error you are receiving states the exact cause of the issue, there is "no suitable method found for totalInventoryValue(double). What this means is there is currently no method named totalInventoryValue() which accepts a double as a parameter.
    When it comes to developing with GUIs I try to ensure the program can work without one. There is a lot of code in the GUI which would be better placed in the OfficeSupplies class such as item creation. The GUI would then make a single call to a new addItem() method within the OfficeSupplies() class which then creates a new instance of DeskItem based on this information passed in.

    Your OfficeSupplies class would need some work so that it is just contains an array of DeskItem a totalInventoryValue method s well as a displayOfficeSupplies() or toString() method.
    The DeskItem class should not extend OfficeSupplies and don't bother with a 'totalValue' variable. If the stock price or quantity changes then this would have to be recalculated so you might as well do this when you want to know the value.

    I know all this may mean a rethink on the project but I will be more than happy to help you with it.

    Regards.
    Ggrammer likes this.

  12. #12
    Ggrammer is offline Member
    Join Date
    Mar 2013
    Posts
    6
    Rep Power
    0

    Default Re: Finding it difficult to calculate total value and use currency format with GUI

    Hello Ronin,

    First off I would like to apologize for taking so long to reply. I have ran into several extremely hectic weeks. I also really appreciate your offer to help me with this program. I am still extremely new to programming and have also began learning another language. I am finished with excuses and ready to get down to business I would be grateful to rework this program with your suggestions when you can find the available time to reply. I do understand that we have busy schedules and do not demand your time if you are not available. I only hope that I may gain enough experience pay the help I have received forward.

    Quote Originally Posted by Ronin View Post
    Hi Ggrammer,

    The error you are receiving states the exact cause of the issue, there is "no suitable method found for totalInventoryValue(double). What this means is there is currently no method named totalInventoryValue() which accepts a double as a parameter.
    When it comes to developing with GUIs I try to ensure the program can work without one. There is a lot of code in the GUI which would be better placed in the OfficeSupplies class such as item creation. The GUI would then make a single call to a new addItem() method within the OfficeSupplies() class which then creates a new instance of DeskItem based on this information passed in.

    Your OfficeSupplies class would need some work so that it is just contains an array of DeskItem a totalInventoryValue method s well as a displayOfficeSupplies() or toString() method.
    The DeskItem class should not extend OfficeSupplies and don't bother with a 'totalValue' variable. If the stock price or quantity changes then this would have to be recalculated so you might as well do this when you want to know the value.

    I know all this may mean a rethink on the project but I will be more than happy to help you with it.

    Regards.

  13. #13
    Ronin is offline Senior Member
    Join Date
    Oct 2010
    Posts
    393
    Rep Power
    5

    Default Re: Finding it difficult to calculate total value and use currency format with GUI

    Hi Ggrammer,

    I'm currently in the process of relocating so am only able to get on here at the weekends for the next couple of weeks but I will help you out as best I can.
    Have you managed to get to grips with OO (Object Orientated) concepts yet? If not then we can revisit these.

    Assuming you are ok with OO then for your program I would use two classes, one for the Item/Product and one for the Inventory(A class to hold the array of Items). I would also use an additional class to hold the main method which will create, populate and test the Inventory class. Later on when you want to add a GUI this could be swapped out or modified to something more appropriate.
    If you wish, you could just start with a Product class and ensure this does everything you want it to for a single product.

    Either way, I would suggest starting with a list of required functionality and attributes for each of the classes. You could use the slightly more formal ULM approach but small projects such as this you could get away with missing this out.

    When coding, don't include any print() or println() statements within the object classes. instead use a return type of String on your methods and let the calling class print out the value returned from these methods. For example in a basic console application this would probably be the main method which would use these statements. Within a GUI however, the values returned could be used to populate a text field something which could not be achieved by using a println() statement.

    If you are able to have a go at this (even something basic) by Monday then I could point you in the right direction before I lose connection again until Friday.

    Regards.

Similar Threads

  1. Finding math.min/max and total
    By jrandaz in forum New To Java
    Replies: 2
    Last Post: 03-18-2012, 01:46 AM
  2. Finding it difficult to understand java
    By Gousia in forum New To Java
    Replies: 34
    Last Post: 06-28-2011, 07:04 PM
  3. How to calculate total in table?
    By ninjalord918 in forum AWT / Swing
    Replies: 8
    Last Post: 07-30-2010, 06:14 AM
  4. Replies: 2
    Last Post: 12-10-2009, 01:06 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •