Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 10 of 10

Thread: Simple problem...

  1. #1
    Member
    Join Date
    Dec 2010
    Posts
    69
    My Mood
    Busy
    Thanks
    4
    Thanked 0 Times in 0 Posts

    Default Simple problem...

    Ok, I'm sure this problem is simple but I can't seem to figure it out. I'm basically making a pseudo-vending machine and trying to get the "dime" and "nickel" buttons to work. Whenever a user presses it, it adds to a variable and accrues (and while accrueing, if it reaches a certain number like $0.90 then it allows the button "Water" to be visible)

    The issue is that my nickels button (its like them adding a nickel to the machine) allows me to accrue up to the 90cents mark and right on $0.90 it allows the Water button to become visible, but when accrueing using JUST the "dimes" button, it has to wait till it reaches $1.00 then once it says a dollar, it pops up allowing you to see the Water button. If at any time I click the Nickel button (like accrue 0.10 in nickels and then .80 cents in dimes, it makes the Water button visible on .90...)



        public void actionPerformed(ActionEvent e)	{
            Object source = e.getSource();
            if (source == depositNickelButton) {
    			v.credit += 0.05;
    			if (v.credit >= v.price)
    				setButtonEnabled(true);
    			messageField.setText(cf.format(v.credit));
    			if (v.credit >= v.price2)
    				setSlot6Enabled(true);
    			messageField.setText(cf.format(v.credit));
    			if (v.credit >= v.price3)
    				setSlot5Enabled(true);
    			messageField.setText(cf.format(v.credit));
    		}
    		if (source == depositDimeButton) {
    			v.credit += 0.10;
    			if (v.credit >= v.price)
    				setButtonEnabled(true);
    			messageField.setText(cf.format(v.credit));
    			if (v.credit >= v.price2)
    				setSlot6Enabled(true);
    			messageField.setText(cf.format(v.credit));
     
    			if (v.credit >= v.price3)
    				setSlot5Enabled(true);
    			messageField.setText(cf.format(v.credit));
     
    		}


  2. #2
    Banned
    Join Date
    May 2010
    Location
    North Central Illinois
    Posts
    1,631
    My Mood
    Sleepy
    Thanks
    390
    Thanked 112 Times in 110 Posts

    Default Re: Simple problem...

    First of all, after each if statement, since there's no bracket..it only executes the line right after it.

    Second...this problem could likely be on your pricing perhaps. Nothing in the code you've posted seems to cause that error that I can find.

    However, would it hurt if you had it set the message field to the credit...even if it's not equal to the lowest amount? I mean...all vending machines show the credit.

    Also, you don't have to have the water button invisible till it reaches a certain amount. You could just have it not enabled.

    WaterButton.setEnabled(false);

    If you posted the entire code...things might be a bit clearer.

    It could be for all I know that it's incrementing but not telling you that it is.

    Try putting printlines after every time you increase the credit to see what it's value actually is.



    public void actionPerformed(ActionEvent e)  {
            Object source = e.getSource();
            if (source == depositNickelButton) {
                v.credit += 0.05;
    System.out.println(v.credit);
                if (v.credit >= v.price)
    {
                    setButtonEnabled(true);
                messageField.setText(cf.format(v.credit));
    System.out.println(v.credit);
    }
                if (v.credit >= v.price2)
    {
                    setSlot6Enabled(true);
                messageField.setText(cf.format(v.credit));
    System.out.println(v.credit);
    }
                if (v.credit >= v.price3)
    {
                    setSlot5Enabled(true);
                messageField.setText(cf.format(v.credit));
    System.out.println(v.credit);
    }
            }
           if (source == depositDimeButton) {
                v.credit += 0.10;
    System.out.println(v.credit);
     
                if (v.credit >= v.price)
    {
                    setButtonEnabled(true);
    System.out.println(v.credit);
                messageField.setText(cf.format(v.credit));
    System.out.println(v.credit);
    }
                if (v.credit >= v.price2)
    {
    System.out.println(v.credit);
                    setSlot6Enabled(true);
                messageField.setText(cf.format(v.credit));
    System.out.println(v.credit);
    }
                if (v.credit >= v.price3)
    System.out.println(v.credit);
                    setSlot5Enabled(true);
                messageField.setText(cf.format(v.credit));
    System.out.println(v.credit);
     
            }
    Last edited by javapenguin; February 4th, 2011 at 11:46 PM.

  3. #3
    Member
    Join Date
    Dec 2010
    Posts
    69
    My Mood
    Busy
    Thanks
    4
    Thanked 0 Times in 0 Posts

    Default Re: Simple problem...

    I was thinking it had something to do with that too so that was among the first things i tried to use, and it didn't work. (it still waits until I hit $1.00 then displays the "Water" button, when it should display at $.90) I think I may have an error in this section:
        public boolean orderBeverage(int slot)	{
            if (credit < price)
                return false;
     
            Beverage b = stock[slot];
            if (b.quantity <= 0)
                return false;
            if (slot == 5){
    				credit = credit - price3;
    				return true;
    		}
    		if (slot == 6){
    			credit = credit - price2;
    			return true;
    		}
     
            b.quantity--;
            credit = credit - price;
            return true;
     
        }	// end orderBevarage METHOD

    but to uncomplicate things, here is all the coding:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.text.*;
     
    public class VendingMachineApplet extends JApplet	{
     
        public void init()	{
            JPanel panel = new VendingMachinePanel();
            this.add(panel);
            setSize(470,350);
     
        }	// end init METHOD
    }	// end VendingMachineApplet CLASS
     
    class VendingMachinePanel extends JPanel implements ActionListener	{
     
        VendingMachine v = new VendingMachine(1.30, 1.10, 0.90);
    	private JLabel depositLabel,
    				   spaceLabel,
    				   slot0Label,
    				   slot1Label,
    				   slot2Label,
    				   slot3Label,
    				   slot4Label,
    				   slot5Label,
    				   slot6Label,
    				   slot7Label,
    				   msgLabel;
        private JTextField messageField;
        private JButton depositQuarterButton,
                        depositDollarButton,
                        depositNickelButton,
                        depositDimeButton,
                        refundButton,
                        slot0Button,
                        slot1Button,
                        slot2Button,
                        slot3Button,
                        slot4Button,
                        slot5Button,
                        slot6Button,
                        slot7Button;
     
        NumberFormat cf = NumberFormat.getCurrencyInstance();
     
        public VendingMachinePanel()	{
            // set the layout mode for the panel
            setLayout(new GridBagLayout());
     
            // load the vending machine
            v.load(0, new Beverage("Pepsi", v.CAPACITY));
            v.load(1, new Beverage("Diet Pepsi", v.CAPACITY));
            v.load(2, new Beverage("Mountain Dew", v.CAPACITY));
            v.load(3, new Beverage("Dr. Pepper", v.CAPACITY));
            v.load(4, new Beverage("Root Beer", v.CAPACITY));
            v.load(5, new Beverage("Water", v.CAPACITY));
            v.load(6, new Beverage("Lemonade", v.CAPACITY));
            v.load(7, new Beverage("Seven-Up", v.CAPACITY));
    		//deposit nickel button
    		depositNickelButton = new JButton("Nickel");
    		setWidth(depositNickelButton, 100);
    		depositNickelButton.addActionListener(this);
    		this.add(depositNickelButton, getConstraints(0,0,1,1, GridBagConstraints.NORTH));
    		 //deposit dime button
    		depositDimeButton = new JButton("Dime");
    		setWidth(depositDimeButton, 100);
    		depositDimeButton.addActionListener(this);
    		this.add(depositDimeButton, getConstraints(0,1,1,1, GridBagConstraints.WEST));
     
            //deposit quarter button
            depositQuarterButton = new JButton("Quarter");
            setWidth(depositQuarterButton, 100);
            depositQuarterButton.addActionListener(this);
            this.add(depositQuarterButton, getConstraints(0,2,1,1, GridBagConstraints.WEST));
     
            //deposit dollar button
            depositDollarButton = new JButton("Dollar");
            setWidth(depositDollarButton, 100);
            depositDollarButton.addActionListener(this);
            this.add(depositDollarButton, getConstraints(0,3,1,1, GridBagConstraints.WEST));
     
    		//deposited label
    		depositLabel = new JLabel("      Deposited");
    		this.add(depositLabel, getConstraints(0,4,1,1, GridBagConstraints.WEST));
            // message field
            messageField = new JTextField(6);
            messageField.setEditable(false);
            this.add(messageField, getConstraints(0,5,1,1, GridBagConstraints.CENTER));
     
            //refund button
            refundButton = new JButton("Refund");
            setWidth(refundButton, 100);
            refundButton.addActionListener(this);
            this.add(refundButton, getConstraints(0,6,1,1, GridBagConstraints.WEST));
     
            //slot 0 button
            slot0Button = new JButton(v.getName(0));
            setWidth(slot0Button, 120);
            slot0Button.addActionListener(this);
            this.add(slot0Button, getConstraints(2,0,1,1, GridBagConstraints.CENTER));
     
    		slot0Label = new JLabel("$1.30");
    		this.add(slot0Label, getConstraints(4,0,1,1, GridBagConstraints.EAST));
     
            //slot 1 button
            slot1Button = new JButton(v.getName(1));
            setWidth(slot1Button, 120);
            slot1Button.addActionListener(this);
            this.add(slot1Button, getConstraints(2,1,1,1, GridBagConstraints.CENTER));
     
    		//slot 1 label
    		slot0Label = new JLabel("$1.30");
    		this.add(slot0Label, getConstraints(4,1,1,1, GridBagConstraints.EAST));
     
            //slot 2 button
            slot2Button = new JButton(v.getName(2));
            setWidth(slot2Button, 120);
            slot2Button.addActionListener(this);
            this.add(slot2Button, getConstraints(2,2,1,1, GridBagConstraints.CENTER));
     
    		//slot 2 label
    		slot0Label = new JLabel("$1.30");
    		this.add(slot0Label, getConstraints(4,2,1,1, GridBagConstraints.EAST));
     
            //slot 3 button
            slot3Button = new JButton(v.getName(3));
            setWidth(slot3Button, 120);
            slot3Button.addActionListener(this);
            this.add(slot3Button, getConstraints(2,3,1,1, GridBagConstraints.CENTER));
     
    		//slot 3 label
    		slot0Label = new JLabel("$1.30");
    		this.add(slot0Label, getConstraints(4,3,1,1, GridBagConstraints.EAST));
     
            //slot 4 button
            slot4Button = new JButton(v.getName(4));
            setWidth(slot4Button, 120);
            slot4Button.addActionListener(this);
            this.add(slot4Button, getConstraints(2,4,1,1, GridBagConstraints.CENTER));
     
    		//slot 4 label
    		slot0Label = new JLabel("$1.30");
    		this.add(slot0Label, getConstraints(4,4,1,1, GridBagConstraints.EAST));
     
            //slot 5 button
            slot5Button = new JButton(v.getName(5));
            setWidth(slot5Button, 120);
            slot5Button.addActionListener(this);
            this.add(slot5Button, getConstraints(2,6,1,1, GridBagConstraints.CENTER));
     
    		//slot 5 label
    		slot0Label = new JLabel("$1.30");
    		this.add(slot0Label, getConstraints(4,5,1,1, GridBagConstraints.EAST));
     
            //slot 6 button
            slot6Button = new JButton(v.getName(6));
            setWidth(slot6Button, 120);
            slot6Button.addActionListener(this);
            this.add(slot6Button, getConstraints(2,7,1,1, GridBagConstraints.CENTER));
     
    		//slot 6 label
    		slot0Label = new JLabel("$0.90");
    		this.add(slot0Label, getConstraints(4,6,1,1, GridBagConstraints.EAST));
     
            //slot 7 button
            slot7Button = new JButton(v.getName(7));
            setWidth(slot7Button, 120);
            slot7Button.addActionListener(this);
            this.add(slot7Button, getConstraints(2,5,1,1, GridBagConstraints.CENTER));
     
    		//slot 7 label
    		slot0Label = new JLabel("$1.10");
    		this.add(slot0Label, getConstraints(4,7,1,1, GridBagConstraints.EAST));
     
        }
     
        // a method for setting grid bag constraints
        private GridBagConstraints getConstraints(int gridx, int gridy,
        int gridwidth, int gridheight, int anchor)	    {
            GridBagConstraints c = new GridBagConstraints();
            c.insets = new Insets(5, 5, 5, 5);
            c.ipadx = 0;
            c.ipady = 0;
            c.gridx = gridx;
            c.gridy = gridy;
            c.gridwidth = gridwidth;
            c.gridheight = gridheight;
            c.anchor = anchor;
            return c;
        }	// end getConstraints METHOD
     
        // a utility method to set the button sizes
        private void setWidth(JComponent c, int width)	{
    		c.setPreferredSize(new Dimension(width, 25));
        }	// end setWidth METHOD
     
        public void setButtonEnabled(boolean b)	{
            slot0Button.setEnabled(b);
            slot1Button.setEnabled(b);
            slot2Button.setEnabled(b);
            slot3Button.setEnabled(b);
            slot4Button.setEnabled(b);
            slot5Button.setEnabled(b);
            slot6Button.setEnabled(b);
            slot7Button.setEnabled(b);
        }	// end setButtonEnabled METHOD
    	public void setSlot6Enabled(boolean b) {
    		slot6Button.setEnabled(b);
    	}
    	public void setSlot5Enabled(boolean b) {
    		slot5Button.setEnabled(b);
    	}
        public void actionPerformed(ActionEvent e)	{
            Object source = e.getSource();
            if (source == depositNickelButton) {
    			v.credit += 0.05;
    			if (v.credit >= v.price)
    				setButtonEnabled(true);
    			messageField.setText(cf.format(v.credit));
    			if (v.credit >= v.price2)
    				setSlot6Enabled(true);
    			messageField.setText(cf.format(v.credit));
    			if (v.credit >= v.price3)
    				setSlot5Enabled(true);
    			messageField.setText(cf.format(v.credit));
    		}
    		if (source == depositDimeButton) {
    			v.credit += 0.10;
    			if (v.credit >= v.price)
    			{
                    setButtonEnabled(true);
                messageField.setText(cf.format(v.credit));
    		}
            else    if (v.credit >= v.price2)
         {           setSlot6Enabled(true);
                messageField.setText(cf.format(v.credit));
    }
           else     if (v.credit >= v.price3)
    {
                    setSlot5Enabled(true);
                messageField.setText(cf.format(v.credit));
    }
     
    		}
            if (source == depositQuarterButton)	{
                v.credit += 0.25;
                if (v.credit >= v.price)
                    setButtonEnabled(true);
                messageField.setText(cf.format(v.credit));
    			if (v.credit >= v.price2)
    				setSlot6Enabled(true);
    			messageField.setText(cf.format(v.credit));
    			if (v.credit >= v.price3)
    				setSlot5Enabled(true);
    			messageField.setText(cf.format(v.credit));
            }	// end OUTER IF
            if (source == depositDollarButton)	{
                v.credit += 1.00;
                if (v.credit >= v.price)
                    setButtonEnabled(true);
                messageField.setText(cf.format(v.credit));
    			if (v.credit >= v.price2)
    				setSlot6Enabled(true);
    			messageField.setText(cf.format(v.credit));
    			if (v.credit >= v.price3)
    				setSlot5Enabled(true);
    			messageField.setText(cf.format(v.credit));
            }	// end OUTER ELSE IF
            else if (source == slot0Button)
                order(0);
            else if (source == slot1Button)
                order(1);
            else if (source == slot2Button)
                order(2);
            else if (source == slot3Button)
                order(3);
            else if (source == slot4Button)
                order(4);
            else if (source == slot5Button)
                order(5);
            else if (source == slot6Button)
            	order(6);
            else if (source == slot7Button)
            	order(7);
            else if (source == refundButton)	{
                double refund = v.refund();
                messageField.setText(cf.format(0.0));
                JOptionPane.showMessageDialog(this, "Please take your change of " + cf.format(refund));
                setButtonEnabled(false);
            }	// end ELSE IF
        }	// end actionPerformed METHOD
     
        public void order(int slot)	    {
            if (v.orderBeverage(slot))	    {
                JOptionPane.showMessageDialog(this, "Enjoy your " + v.getName(slot));
                messageField.setText(cf.format(v.credit));
                if (v.credit < v.price)
                    setButtonEnabled(false);
    		}	// end OUTER IF
            else
                JOptionPane.showMessageDialog(this, v.getName(slot) + " is out of stock");
                //messageField.setText("Out of Stock");
        }	// end order METHOD
    }	// end VendingMachinePanel CLASS
    public class VendingMachine	{
    	// the number of different types of beverages the machine can hold
        public static final int SLOTS = 8;
     
    	//the number of bottles of each beverage the machine can hold
        public static final int CAPACITY = 10;
     
    	// the price per beverage, set via the constructor
        public double price;
    	public double price2;
    	public double price3;
        // the amount the user has entered
        public double credit = 0.0;
     
        Beverage[] stock = new Beverage[SLOTS];
     
        public VendingMachine(double p, double p2, double p3)
        {	price = p;
        	price2 = p2;
        	price3 = p3;}	// end CONSTRUCTOR
     
        public void load(int slot, Beverage bev)	{
            if (slot < SLOTS)
                stock[slot] = bev;
        }	// end load METHOD
     
        public double depositMoney(double amount)	{
            credit += amount;
            return credit;
        }	// end depositMoney METHOD
     
        public boolean orderBeverage(int slot)	{
            if (credit < price)
                return false;
     
            Beverage b = stock[slot];
            if (b.quantity <= 0)
                return false;
            if (slot == 5){
    				credit = credit - price3;
    				return true;
    		}
    		if (slot == 6){
    			credit = credit - price2;
    			return true;
    		}
     
            b.quantity--;
            credit = credit - price;
            return true;
     
        }	// end orderBevarage METHOD
     
        public double refund()	{
            double refund = credit;
            credit = 0.0;
            return refund;
        }	// end refund METHOD
     
        public String getName(int slot)	{
            if (slot < SLOTS)
                return ((Beverage)stock[slot]).name;
            else
                return "Bad slot";
        }	// end getNam METHOD
     
    }	// end VendingMachine CLASS
    public class Beverage	{
    	public String name;
    	public int quantity;
     
    	public Beverage(String n, int q)	{
    		name = n;
    		if (q > VendingMachine.CAPACITY)
    			quantity = VendingMachine.CAPACITY;
    		else
    			quantity = q;
    	}	// end CONSTRUCTOR
    }	// end Beverage CLASS
    Last edited by _lithium_; February 4th, 2011 at 11:54 PM.

  4. #4
    Member
    Join Date
    Dec 2010
    Posts
    69
    My Mood
    Busy
    Thanks
    4
    Thanked 0 Times in 0 Posts

    Default Re: Simple problem...



    That is the incrementing (i put a print line like you suggested)...why would it do that?

  5. #5
    Super Moderator helloworld922's Avatar
    Join Date
    Jun 2009
    Posts
    2,895
    Thanks
    23
    Thanked 619 Times in 561 Posts
    Blog Entries
    18

    Default Re: Simple problem...

    This is a problem with using floating points and truncation errors. The simplest solution is to represent the money amount using integers for cents. You can then get the dollar amounts back using money/100, and use money%100 for the cents amounts.

    int money = 100 * 5 + 90; // $5.90
    System.out.println("$" + money/100 + "." + money%100);

  6. The Following User Says Thank You to helloworld922 For This Useful Post:

    javapenguin (February 5th, 2011)

  7. #6
    Member
    Join Date
    Dec 2010
    Posts
    69
    My Mood
    Busy
    Thanks
    4
    Thanked 0 Times in 0 Posts

    Default Re: Simple problem...

    Why wouldn't this occur with the Nickel button though? Why only the dimes? I can't change it to int from double cause it then keeps telling me its a loss of precision and it is expecting a double.

  8. #7
    Member
    Join Date
    Dec 2010
    Posts
    69
    My Mood
    Busy
    Thanks
    4
    Thanked 0 Times in 0 Posts

    Default Re: Simple problem...

    ?? Any suggestions?

  9. #8
    Super Moderator helloworld922's Avatar
    Join Date
    Jun 2009
    Posts
    2,895
    Thanks
    23
    Thanked 619 Times in 561 Posts
    Blog Entries
    18

    Default Re: Simple problem...

    It's due to how floating points are represented. The math is rather involved, but if you're interested, see IEEE 754-2008 - Wikipedia, the free encyclopedia.

    One solution is to replace everywhere it states double with integer (as I stated above). You'll need to adjust your math accordingly (increasing the value by 5 for nickels, increasing by 10 for dimes).

    Something else you could try is implement the greater than to be at a half cent, since very rarely will you get an error to propagate up that much.

    double sodaPrice = 0.895; // really costs 0.90
    double money = 0;
    for(int i = 0; i < 9; ++i)
    {
        money += 0.1;
    }
    System.out.println("Do you have enough money? " + (sodaPrice < money));

  10. #9
    Member
    Join Date
    Dec 2010
    Posts
    69
    My Mood
    Busy
    Thanks
    4
    Thanked 0 Times in 0 Posts

    Default Re: Simple problem...

    Yeah i attempted to switch everything to integers but it won't allow me to because I need to pass .9 to the constructor and it flags it as a double.

  11. #10
    Super Moderator helloworld922's Avatar
    Join Date
    Jun 2009
    Posts
    2,895
    Thanks
    23
    Thanked 619 Times in 561 Posts
    Blog Entries
    18

    Default Re: Simple problem...

    Does it need to be (i.e. external constraint), or you don't want to change it?

    It's possible to convert between the double and integer formats, though as the compiler's warning you against, you could lose precision (for money, it's almost always negligible)

    double moneyD = 1.3; // $1.30
    int moneyI = (int) moneyD * 100; // need an explicit cast, moneyI = 130

Similar Threads

  1. Simple beginers problem
    By vycka1990 in forum What's Wrong With My Code?
    Replies: 4
    Last Post: November 18th, 2010, 12:00 PM
  2. Simple Actionlistener problem
    By olemagro in forum AWT / Java Swing
    Replies: 5
    Last Post: October 11th, 2010, 10:46 AM
  3. SOAP / WSDL Simple (ish) Problem
    By Mezz in forum Java Networking
    Replies: 0
    Last Post: September 29th, 2010, 12:01 PM
  4. Simple import problem
    By Mekster in forum Java IDEs
    Replies: 3
    Last Post: November 13th, 2009, 09:17 PM
  5. Simple scanner problem
    By Sinensis in forum File I/O & Other I/O Streams
    Replies: 4
    Last Post: September 20th, 2009, 09:01 PM