(simple) Prices and Ordering


DevX Home    Today's Headlines   Articles Archive   Tip Bank   Forums   

Results 1 to 8 of 8

Thread: (simple) Prices and Ordering

  1. #1
    Join Date
    Feb 2005
    Posts
    3

    (simple) Prices and Ordering

    Hello folks, I am having trouble coding a program and was hoping I could get some help/advice here. I am new to java and am trying to learn from experienced programmers, tutorials and text books. Here is the problem


    Shop sells (for example)-

    Bolts - 5 cent per unit
    Nut - 3 cent per unit
    Washer - 1 cent per unit

    Basically I need a simple program that asks a user for the number of units of bolts, nuts and washers they want to purchase, calculates this and prints the total.

    But as an extra I need it to check the order, if there is more bolts than nuts the order is wrong and if there is more washers than bolts the order will also be wrong.

    So i need it to write out either "Order incorrect" or "Order is OK" followed by the total price.

  2. #2
    Join Date
    Jan 2005
    Posts
    61
    I'm in about the same boat as you in the ways I am trying to learn Java, so apologies if my suggestions are a bit basic.

    It sounds like you've already got the products, user input and calculation sorted, so for the nuts > bolts thing, you could use an if / else statement, or possibly (I think) a switch statement instead.

    I might have a go at this one myself - it'll make a change to bang my head over a different problem

  3. #3
    Join Date
    Nov 2004
    Location
    Norway
    Posts
    1,560
    I hope I haven't robbed you of the opportunity to create
    this yourself, but since you are a selfconfessed newbie
    I thougt it would be ok to present you with a complete
    (?) and standard solution so you don't waste a lot of
    time trying out stuff that does not work.

    However I hope you take the time to understand what
    this little how-to-boil-an-egg excercise does.


    Code:
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    
    public class Nuts extends JFrame implements ActionListener {
    
      static int PRICE_BOLT=5;
      static int PRICE_NUT=3;
      static int PRICE_WASHER=1;
    
      // define components
      BorderLayout borderLayout1 = new BorderLayout();
      JPanel buttonPanel = new JPanel();
      JPanel centerPanel = new JPanel();
      JButton purchaseBtn = new JButton();
      JButton closeBtn = new JButton();
      JButton resetBtn = new JButton();
      GridLayout gridLayout1 = new GridLayout();
      JLabel boltLbl = new JLabel();
      JLabel washerLbl = new JLabel();
      JLabel nutLbl = new JLabel();
      JLabel totalLbl = new JLabel();
      JTextField washersTF = new JTextField();
      JTextField nutsTF = new JTextField();
      JTextField boltsTF = new JTextField();
    
      /**
       * CONSTRUCTOR
       */
      public Nuts() {
        super ("Nuts & Bolts & Stuff");
        try {
          jbInit();
        }
        catch(Exception e) {
          e.printStackTrace();
        }
    
        // hook up buttons to this frame's eventhandler
        purchaseBtn.addActionListener(this);
        closeBtn.addActionListener(this);
        resetBtn.addActionListener(this);
    
        // ensure that program exits properly
        addWindowListener(new WindowAdapter() {
          public void windowClosing(WindowEvent e) {
            System.exit(0);
          }
        });
      }
      /**
       * Handle button clicks
       * @param e
       */
      public void actionPerformed(ActionEvent e) {
        if (e.getSource()==closeBtn) System.exit(0);
        if (e.getSource()==resetBtn) {
          nutsTF.setText("");
          boltsTF.setText("");
          washersTF.setText("");
          totalLbl.setText("");
          return;
        }
        // it must be the purchase button...
        try {
          calculateTotal();
        } catch (Exception ex) {
          // The user goofed, show an error dialog
          JOptionPane.showMessageDialog(this,ex.getMessage(),
                                        "Order not accepted",
                                        JOptionPane.ERROR_MESSAGE);
        }
      }
      /**
       * Get an integer value from a named textField,
       * throw exception for invalid entry.
       * @param tf
       * @param tfName
       * @return
       */
      private int getValue(JTextField tf, String tfName)  throws Exception {
        try {
          return Integer.parseInt(tf.getText().trim());
        } catch (NumberFormatException nfe) {
          throw new Exception ("The value entered for "+tfName+" is an invalid numeric entry");
        }
      }
      /**
       * Calculate the total, if the user enters invalid integers or breaks the
       * old RULES OF THE NUTS an exception is thrown.  This will be caught as it
       * 'bubbles up' to the try-catch in the actionPerformed() method
       * @throws Exception
       */
      private void calculateTotal () throws Exception {
        int nuts=getValue(nutsTF,"NUTS");
        int bolts=getValue(boltsTF, "BOLTS");
        int washers=getValue(washersTF,"WASHERS");
        if (bolts > nuts) {
          throw new Exception ("Seriously !! You cannot buy more bolts that nuts !!");
        }
        if (washers > bolts) {
          throw new Exception ("GASP !! You are attempting to buy more washers than bolts !!");
        }
        int total=bolts*PRICE_BOLT + nuts*PRICE_NUT + washers*PRICE_WASHER;
        totalLbl.setText("Total: "+total+" cent");
      }
      public static void main(String[] args) {
        Nuts nuts = new Nuts();
        nuts.setBounds(10,10,450,140);
        nuts.setVisible(true);
      }
      /**
       * Set up GUI
       * @throws Exception
       */
      private void jbInit() throws Exception {
        this.getContentPane().setLayout(borderLayout1);
        purchaseBtn.setText("Purchase");
        closeBtn.setText("Close");
        centerPanel.setLayout(gridLayout1);
        gridLayout1.setColumns(2);
        gridLayout1.setRows(3);
        gridLayout1.setHgap(4);
        gridLayout1.setVgap(4);
        boltLbl.setText("Bolts (5 cent per unit)");
        boltsTF.setHorizontalAlignment(SwingConstants.RIGHT);
        washerLbl.setText("Washers (1 cent per unit)");
        nutLbl.setText("Nuts (3 cent per unit)");
        nutsTF.setText("");
        nutsTF.setHorizontalAlignment(SwingConstants.RIGHT);
        washersTF.setText("");
        washersTF.setHorizontalAlignment(SwingConstants.RIGHT);
        totalLbl.setBorder(BorderFactory.createLineBorder(Color.black));
        totalLbl.setPreferredSize(new Dimension(150, 22));
        totalLbl.setHorizontalAlignment(SwingConstants.CENTER);
        totalLbl.setText("");
        resetBtn.setPreferredSize(new Dimension(80, 25));
        resetBtn.setText("Reset");
        buttonPanel.add(purchaseBtn, null);
        centerPanel.add(boltLbl, null);
        centerPanel.add(boltsTF, null);
        centerPanel.add(nutLbl, null);
        centerPanel.add(nutsTF, null);
        centerPanel.add(washerLbl, null);
        centerPanel.add(washersTF, null);
        buttonPanel.add(totalLbl, null);
        buttonPanel.add(resetBtn, null);
        buttonPanel.add(closeBtn, null);
        this.getContentPane().add(buttonPanel, BorderLayout.SOUTH);
        this.getContentPane().add(centerPanel, BorderLayout.CENTER);
      }
    
    }
    eschew obfuscation

  4. #4
    Join Date
    Feb 2005
    Posts
    3
    Wow, I am nowhere near that level and dont expect to be anytime either! Thats excellent thanks! I find it a little hard to understand at the moment, currently I have been sticking to public static void main and am learning about arrays, strings, if/else, output and input. Im sure thats laughable to you :P I have been trying to code this in a compiler in its simplest format to no avail, Hopefully I will learn something from your coding, thanks a lot!

  5. #5
    Join Date
    Jan 2005
    Posts
    61
    It's not laughable at all - it's great to find someone in the same position as I am

    We've all got to start somewhere I guess - you and I will get there eventually

  6. #6
    Join Date
    Nov 2004
    Location
    Norway
    Posts
    1,560
    Yea, thats right. Like, when people ask me "is it difficult
    to learn how to be a good programmer ?", I just say "NO,
    its just like learning a new language or two, like chinese
    and zwahili"
    eschew obfuscation

  7. #7
    Join Date
    Mar 2004
    Posts
    635
    or latin.(its what i took for some odd reason)

    I would make 3 JTextField()'s and 1 JButton()'s. The button would be the calculate button. You could label each text field with a JLabel(). When the user clicks the button to calculate the final price, do a check on the numbers first. Make sure each field has a number entered, or have them initialized with 0 from the start. Make sure the the numbers match up.

    //if numbers do not match
    if (!(washers == bolts))
    print an error message.


    However, some people do buy more washers than bolts because they use them as spacers. Just thought I'd point that out.

    Just break down each part of the program, and go from there.

  8. #8
    Join Date
    Feb 2005
    Posts
    3
    Thanks to everyone for your help and advice, hopefully I can learn a lot from reading these boards!!

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center
 
 
FAQ
Latest Articles
Java
.NET
XML
Database
Enterprise
Questions? Contact us.
C++
Web Development
Wireless
Latest Tips
Open Source


   Development Centers

   -- Android Development Center
   -- Cloud Development Project Center
   -- HTML5 Development Center
   -- Windows Mobile Development Center