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 8 of 8

Thread: Vending Machine

  1. #1
    Member
    Join Date
    Jan 2014
    Location
    Washington DC
    Posts
    81
    Thanks
    12
    Thanked 0 Times in 0 Posts

    Question Vending Machine

    I am having a difficult time writing what started out as a simple vending machine program. As I go on though, it seems that I'm overcomplicating it and it is getting messy, so I have resorted to the forum before I really get off the path. Any advice on how to clean it up? I'm going to list a few of the problems I am having with the code below:
    1. The user is supposed to enter his/her money and the program is to read each value separately (Do-While loop) and keep a running total of the money entered. I can't seem to get the right code format to do this. I was trying to do this with the variable total and so that is why the total exists in the switch statement, but it did not work.

    2. In the second Do-While statement, is there a way to kick back an error when their are insufficient funds to purchase an item? Instead of getting a negative change return.

    And any other advice on how I can clean up this code would be great! Thanks a lot and sorry about the mess.

    package practice;
     
    import java.util.Scanner;
     
    public class Practice {
     
        public static void main(String[] args) {
         double count, total;                                      
         int item;                                          
     //Display Available Options To Customer    
         Scanner input = new Scanner(System.in);
         System.out.println("*VENDING MACHINE*");
         System.out.println("1. Snickers");
         System.out.println("2. 100 Grand");   
         System.out.println("3. Pay Day");
         System.out.println("4. Milky Way");
         System.out.println("5. Kit Kat\n");
     
         System.out.println("We accept coins, $1 and $5 bills.");
    //User Input     
      do{
             count = input.nextDouble();
             total = count;
             System.out.println("Please insert your money now. (0 To Exit)");
             System.out.printf("Amount Entered: $%.2f\n" , count);
             if(count >= 0.01 && count <=5){
                //System.out.printf("Amount Entered: $%.2f\n" , count);
                 total = count;
            }
             else if(count > 5) 
                    System.out.println("Please Enter Up To $5.00");
             else
                 break;
            }
                while(count!=0 || count <= 5);               
     
    //Loop That Enables User To Make Multiple Purchases And Record Running Total  
         do{       
             System.out.println("Enter item number (0 to exit):\t");      
             item = input.nextInt();                                    
     
             switch(item){                 
                 case 1: total -= 1.00;
                    System.out.printf("%s%.2f\n","Amount remaining: $" , total); 
                    break;
                 case 2: count -= 1.00;
                    System.out.printf("Amount remaining: $%.2f\n" , count);  
                    break;               
                 case 3: count -= 0.50;
                    System.out.printf("Amount remaining: $%.2f\n" , count);                 
                    break;
                 case 4: count -= 1.25;
                    System.out.printf("Amount remaining: $%.2f\n" , count);  
                    break;
                 case 5: count -= 0.75;
                    System.out.printf("Amount remaining: $%.2f\n" , count);  
                    break;
                 case 0:  
                     break;
             }
         }
                 while(item!=0 && count > 0);                  
                      System.out.println("Please make another selection, or press 0");  
               System.out.printf("Change: $%.2f\n" , count);
               System.out.println("Have a nice day.");
     
         }
    }


  2. #2
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    5,520
    My Mood
    Mellow
    Thanks
    215
    Thanked 698 Times in 680 Posts

    Default Re: Vending Machine

    Welcome to the forum. Thank you for taking the time to learn how to post correctly.

    The order of the statements and therefore the execution of the program matters, and your order is a bit mixed up. I think all of your ideas are solid and you have all of the right pieces, but some are slightly out of order.

    I suggest telling the user what to do, accepting input, and provide feedback as a general rule for the order of things:

    Tell user: Insert money, 0 to exit
    Get user input
    Tell user: Amount entered is:
    If needed, tell user: Changes to make
    Repeat as needed.

    Keeping track of the total: only do that when the correct amount has been entered, then the statement should be:

    total = total + count;

    or

    total += count; // preferred, looks like you've been reading

    The presentation of your menu is also out of place, but I'll have you think about how you might change that. Get the money, then show the candy menu? Show the candy with prices, get the money, then show the candy menu to get the candy choice? Think about how you'd do it in real life as a candy salesman and code it like that.

    Try making those adjustments and then post updated code with any questions or problems you're still having.

  3. The Following User Says Thank You to GregBrannon For This Useful Post:

    javaStooge (January 22nd, 2014)

  4. #3
    Junior Member Tjones787's Avatar
    Join Date
    Jan 2014
    Location
    Lagos, Nigeira
    Posts
    16
    My Mood
    Asleep
    Thanks
    4
    Thanked 1 Time in 1 Post

    Default Re: Vending Machine

    Code Deleted

    There are lot of logic errors in your program.
    (1). You are to print to the user to input there money, before calling the input.nextDouble() and the total variable already assigned to count before the if else statement to check the user input and the break statement in else , breaks the loop if the if else statement is not met.

    (2). The second loop won't end until the user input is negative due to the && bitwise operator . The request to ask the user for another input should be in the loop
    Last edited by GregBrannon; January 22nd, 2014 at 10:33 AM. Reason: Please don't post solutions.
    Tjones787

  5. #4
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    5,520
    My Mood
    Mellow
    Thanks
    215
    Thanked 698 Times in 680 Posts

    Default Re: Vending Machine

    @Tjones787: Please don't post solutions. Provide general guidance, hints, outlines, etc. Read "The Problem With Spoon-feeding" which is a principle that is practiced and enforced on this forum. Also, please review the use of tags for posting code correctly.

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

    Tjones787 (January 22nd, 2014)

  7. #5
    Member
    Join Date
    Jan 2014
    Location
    Washington DC
    Posts
    81
    Thanks
    12
    Thanked 0 Times in 0 Posts

    Default Re: Vending Machine

    I made some of the changes that you advised along with a few additional changes and the output is mucho better! Thank you very much for the advice and assistance.

    I cannot think of any other way to prevent the program from returning a negative change, unless I use an If-Else statement and nest the Switch within the If statement. Is that the only way to avoid the negative return? Is there a limit to the number of nests a programmer should make before it gets confusing or messy. My main concern as a programmer, and any programmer, is to make it as streamlines and readable as possible--so I want to make sure I avoid sloppiness at the beginning of the semester.

    Do you have any advice on how I can limit the number of loops in the Do-While statement. I want to limit the number of times it can run to 4, meaning that the maximum number of choices the user can make are 4 regardless of the amount of money still available.


    package practice;
     
    import java.util.Scanner;
     
    public class Practice {
     
        public static void main(String[] args) {
         double count;
         double total = 0;                                      
         int item;                                          
     //Display Available Options To Customer    
         Scanner input = new Scanner(System.in);
         System.out.printf("%22s\n" ,"*VENDING MACHINE*");
         System.out.printf("1. Snickers%15s\n" , "$1.00");
         System.out.printf("2. 100 Grand%14s\n" , "$1.00");   
         System.out.printf("3. Pay Day%16s\n" , "$0.50");
         System.out.printf("4. Milky Way%14s\n" , "$1.25");
         System.out.printf("5. Kit Kat%17s\n" , "$0.75\n");
     
         System.out.println("Please insert money now. (0 To Exit)");
         System.out.println("We accept coins, $1 and $5 bills.");
    //User Input     
      do{
             count = input.nextDouble();
             total += count;
     
             if(count >= 0.01 && total <5){
                System.out.printf("Amount Entered: $%.2f\n" , total);            
            }
             else if(count > 5) 
                    System.out.println("Please Enter Up To $5.00");
             else
                 break;
            }
                while(count!=0 || count <= 5);               
     
    //Loop That Enables User To Make Multiple Purchases And Record Running Total  
         do{       
             System.out.println("Enter Item Number (0 to exit):\t");      
             item = input.nextInt();                                    
     
             switch(item){                 
                 case 1: total -= 1.00;
                    System.out.printf("%s%.2f\n","Amount remaining: $" , total); 
                    break;
                 case 2: total -= 1.00;
                    System.out.printf("Amount remaining: $%.2f\n" , total);  
                    break;               
                 case 3: total -= 0.50;
                    System.out.printf("Amount remaining: $%.2f\n" , total);                 
                    break;
                 case 4: total -= 1.25;
                    System.out.printf("Amount remaining: $%.2f\n" , total);  
                    break;
                 case 5: total -= 0.75;
                    System.out.printf("Amount remaining: $%.2f\n" , total);  
                    break;
                 case 0: System.out.println();
                     break;
             }
         }
                 while(item!=0 && total > 0);                  
     
               System.out.printf("Change: $%.2f\n\n" , total);
               System.out.println("Have a nice day.");
     
         }
    }

  8. #6
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    5,520
    My Mood
    Mellow
    Thanks
    215
    Thanked 698 Times in 680 Posts

    Default Re: Vending Machine

    Just as with any purchase, the typical approach would be that if the user chooses an item that would return a negative value, which means there is not enough money left for that choice, then the sale would fail, and the user would be given the option to make another choice, or accept their change.

    That thinking suggests your do/switch/while logic could be improved. Do you have to include a switch statement in this project? In any case, the switch statement could be better. Any time you're typing the same code over and over (like the printf() statements in the switch statement), ask yourself, "How can I change it so that SAME STATEMENT only has to occur once? For this switch statement, the answer is fairly obvious, and it gives you the opportunity to do further processing on the resulting total.

    Is there a limit to the number of loops, embedded or otherwise? Technically, no. You want to write code that's readable, easy to follow, and is as efficient as it can be. In my opinion, a loop in a loop is enough. When you get a bit more advanced, you'll learn to use methods other than the main() method. Your current program could benefit by breaking out parts into separate methods. You may not be comfortable with that yet.

    Yes, there are ways to limit the number of times a loop executes. If that's what you want to do, use a counter that keeps track of how many times the loop has executed and dump out when the counter reaches the desired value. Or, accept the user's money as long as there is funding available. When the funding runs out, offer another choice or return the remaining funds. That logic will be done with if statements.

  9. #7
    Member
    Join Date
    Jan 2014
    Location
    Washington DC
    Posts
    81
    Thanks
    12
    Thanked 0 Times in 0 Posts

    Default Re: Vending Machine

    [/COLOR]This part is driving me nuts! I can't work out the correct logic, so that if the user inputs a value greater than 5, the program wont record it as a value in total. I want it to kick back the error to "Enter values less than 5", and for the do-while loop to stop when $5 has been entered or user hits 0. I was staring at this too much last night and I've really confused myself.

        public static void main(String[] args) {
            double count;
            double total = 0; //total keeps a running total of money after purchases are made
            int counter = 1;  //counter is used to limit the maximum purchases to 4  
     
            int item;
    //Display Available Options To Customer    
            Scanner input = new Scanner(System.in);
            System.out.printf("%24s\n", "/*|VENDING MACHINE|*\\");
            System.out.printf("%3s%15s%1s\n", "/" , "---------------------" , "\\");
            System.out.printf("%26s\n", "-------------------------");
            System.out.printf("|| 1. Snickers%13s\n", "$1.00 ||");
            System.out.printf("|| 2. 100 Grand%12s\n", "$1.00 ||");
            System.out.printf("|| 3. Pay Day%14s\n", "$0.50 ||");
            System.out.printf("|| 4. Milky Way%12s\n", "$1.25 ||");
            System.out.printf("|| 5. Kit Kat%14s\n", "$0.75 ||");
            System.out.println(" -------------------------");
            System.out.println("  **                   **");
     
            System.out.println("  Please insert money now.");
            System.out.printf("%18s\n","(0 To Exit)");
            System.out.println(" Accept coins, $1 and $5 bills.");
            System.out.println(" ----------------------------");
            System.out.println(" ----------------------------");
     
    //User Input  
            do {
                System.out.print(" Enter: ");
                count = input.nextDouble();
                //total += count;
                if (count >= 0.01 && count <= 5 && total < 5) {
                    total += count;
                    System.out.printf(" Amount Entered: $%.2f\n", total);                
                } else if (count > 5) {
                    System.out.println(" Please Enter Up To $5.00");
                }
            } while (count != 0 || count <= 5);

  10. #8
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    5,520
    My Mood
    Mellow
    Thanks
    215
    Thanked 698 Times in 680 Posts

    Default Re: Vending Machine

    This is what you said (rephrased and moved around a bit):

    a do-while loop (that accepts up to) $5 or user hits 0 (runs out of money)

    around an if statement:

    if the user inputs a value greater than 5, the program wont record it as a value in total (and) the error to "Enter values less than 5" (is shown)

    Now think through these leading questions: Is there one do/while loop that does as described in the first sentence, or is the accept funds loop different than the spend funds loop? Can they be the same? Should they? Do they need to be?

    Another thought, the statement ( count != 0 || count <= 5 ) has problems.

Similar Threads

  1. Java vending machine, minor thing.
    By Aprok in forum What's Wrong With My Code?
    Replies: 3
    Last Post: October 5th, 2011, 02:35 PM
  2. Moving MySql Database from one machine to another machine
    By vaishali in forum JDBC & Databases
    Replies: 5
    Last Post: July 21st, 2010, 01:21 AM
  3. vending machine submit button help
    By maybach230 in forum Java Applets
    Replies: 3
    Last Post: April 23rd, 2010, 10:16 AM
  4. need help with Vending Machine code...
    By mia_tech in forum Loops & Control Statements
    Replies: 3
    Last Post: April 20th, 2009, 05:24 AM
  5. Replies: 6
    Last Post: November 14th, 2008, 03:09 PM