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."); } }