自动售货机,输入变量未被识别用于计算

时间:2014-05-31 01:33:51

标签: java methods constructor global-variables do-while

我创建了一个自动售货机驱动程序和类。它实际上工作之前,但我试图做一个do-while循环试图给第一个菜单屏幕(InsertMoney)一些验证,当我一周后回来并决定删除该位,它没有得到回到以前的工作状态。

这仅仅是针对SelectItem的InsertMoney方法,它可以从那里完美地工作。

基本上,当你按下“我”时,插入钱,无论你插入什么(paymentSum)没有进行计算,无论你输入什么,它只是给你产品,所有的变化设置为0.我已经过度复杂它试图修复它但我是在这个阶段我不能被细节困扰的阶段,我想要的只是paySum在计算中工作。如果我在任何一个方法的任何阶段都使用paymentSum的JOptionPane输出,它会显示插入的钱,但我不知道为什么它没有用它进行计算。

我只完成了一个学期的编程,所以我想我的代码远远没有优化,但我似乎无法找到问题所在,而且我的大脑已经变得模糊,所以我想知道是否有人可以请求帮助!

驱动程序

import javax.swing.JOptionPane;     // Library for dialog boxes

public class VendingMachineDriver       // Start of VendingMachineDriver class with main method
{
    public static void main (String [] args) {

        // Creating an object of VendingMachine class
        VendingMachine objVendingMachine = new VendingMachine();

        // Start of program repeat loop with constructors from VendingMachine class
        do 
        {
        objVendingMachine.InsertMoney();
        objVendingMachine.SelectItem();
        objVendingMachine.NotEnoughMoney();
        objVendingMachine.GiveChange();
        objVendingMachine.Repeat();
        }       // End of main method do loop

    // Condition for ending program loop
    while (objVendingMachine.again == JOptionPane.YES_NO_OPTION);       
        System.exit(0);
    }
}       // End of VendingMachineDriver class

VendingMachine Class

    import javax.swing.JOptionPane;     // Importing library for dialog boxes
    import java.text.DecimalFormat;     // Importing library for decimal number formatting

    public class VendingMachine         // Start of VendingMachine class with constructors
    {
            String spaymentSum;         // Money inserted by user for parsing into Integer value

            String productName;         // Name of product

            int paymentSum;             // Money inserted by customer parsed into Integer value as pence

            int coke, pepsi, sevenUp, mars, snickers, twix;         // variables for products sold

            int price;              // Value holding the price of product selected
            int changeLeft;         // Change left from inserted money after selection

            int again;              // variable for descerning program repeat


            DecimalFormat pence = new DecimalFormat("#p");      // Format display output for pence


            /**
             * SelectionMenu constructor to display welcome message, money insertion and select item options.
             */

            public void InsertMoney()
            {
                String soption;         // Variable for machine operation
                boolean correctOption = false;  // boolean variable for confirming input validation with default value

                paymentSum = 0;         // Intialising inserted money variable paymentSum

                do      // Start of loop valid option selection loop
                {

                    // Vending machine welcome dialog
                    soption = JOptionPane.showInputDialog(
                        "============================================"
                        + "\nWelcome to the College Vending Machine!" 
                        + "\n============================================"
                        + "\n\nOptions: i for insert money, s for select item, q for quit."
                        + "\n\n============================================");

                    // input validation for only i, s or q user input
                    if (soption.matches("isq"))
                    {
                        JOptionPane.showMessageDialog(null, "Invalid input! Please try again.");    
                    }

                    // start of switch condition to catch specific characters (i, s and q) for machine operation
                    switch (soption) 
                        {
                        case "q":       // user chooses q to quit
                            JOptionPane.showMessageDialog(null, "Have a Nice Day!");
                            System.exit(0);     // terminate application
                            break;
                        case "i":       // if user chooses i: insert money;
                            do 
                            {
                                spaymentSum = JOptionPane.showInputDialog(
                                            "=============================" 
                                            + "\nPlease enter some money (in pence)" 
                                            + "\n=============================");   // Inserting money

                                // Validation against string and decimal numbers
                                if (spaymentSum.matches("[a-zA-Z]+(\\.[0-9]+)?$"))  // Validation against string
                                {
                                    JOptionPane.showMessageDialog(null,"Must be a positive number! Try again.");
                                    spaymentSum = null;
                                }
                                else
                                {
                                    paymentSum = Integer.parseInt(spaymentSum); // Parsing for calculations
                                if (paymentSum <= 0)        // Validation against negative numbers
                                    JOptionPane.showMessageDialog(null,"Must be a positive number! Try again.");
                                }
                            }
                            while (paymentSum <=0);
                            correctOption = true;
                            break;
                        case "s":       // if user chooses s: select item
                            correctOption = true;
                            break;
                        default: 
                            correctOption = false;
                            JOptionPane.showMessageDialog(null, "Incorrect choice entered. Try again.");
                            break;
                        }

                }

                while (correctOption != true);
            }


            /**
             * Start of SelectItem constructor for selection of product
             */

            public void SelectItem()
            {   
                String sproductSelection;       // Variable to detect which product is selected

                productName = " Nothing";   // Default name of product when none is selected

                coke = 60;          // Price for Coke
                pepsi = 75;         // Price for Pepsi
                sevenUp = 70;       // Price for 7Up
                mars = 65;          // Price for Mars
                snickers = 80;      // Price for Snickers
                twix = 55;          // Price for Twix

                    // Product selection screen

                sproductSelection = JOptionPane.showInputDialog(
                            "======================"
                            + "\nCredit: " + pence.format(paymentSum)  
                            + "\n======================"
                            + "\nWhat would you like to buy?" 
                            + "\n\n========"
                            + "\nDRINKS"
                            + "\n========"
                            + "\nC = Coke: " + pence.format(coke)       // Drinks
                            + "\nP = Pepsi: " + pence.format(pepsi) 
                            + "\n7 = 7UP: " + pence.format(sevenUp)
                            + "\n========"
                            + "\nCHOCOLATES"
                            + "\n========"
                            + "\nM = Mars: " + pence.format(mars)       // Chocolates
                            + "\nS = Snickers: " + pence.format(snickers) 
                            + "\nT = Twix: " + pence.format(twix)
                            + "\n======================"
                            + "\n\n");

            do      // Start of do loop to ensure valid product selection
            {           
                // Start of validation loop to repeat if sproductSelection = null (as in incorrect value entered)
                if (null != sproductSelection)

                // Using switch to capture input by user to match selected products
                switch (sproductSelection) 
                    {
                    case "C":
                        price = coke;
                        productName = "Coke";
                        break;
                    case "P":
                        price = pepsi;
                        productName = "Pepsi";
                        break;
                    case "7":
                        price = sevenUp;
                        productName = "7UP";
                        break;
                    case "M":
                        price = mars;
                        productName = "Mars";
                        break;
                    case "S":
                        price = snickers;
                        productName = "Snickers";
                        break;
                    case "T":
                        price = twix;
                        productName = "Twix";
                        break;
                    default:        // If invalid options in case are selected
                        productName = null;
                        JOptionPane.showMessageDialog(null, "Incorrect choice entered. Try again.");
                        sproductSelection = JOptionPane.showInputDialog(
                        "======================"
                        + "\nCredit: " + pence.format(paymentSum)  
                        + "\n======================"
                        + "\nWhat would you like to buy?" 
                        + "\n\n========"
                        + "\nDRINKS"
                        + "\n========"
                        + "\nC = Coke: " + pence.format(coke)       // Drinks
                        + "\nP = Pepsi: " + pence.format(pepsi) 
                        + "\n7 = 7UP: " + pence.format(sevenUp)
                        + "\n========"
                        + "\nCHOCOLATES"
                        + "\n========"
                        + "\nM = Mars: " + pence.format(mars)       // Chocolates
                        + "\nS = Snickers: " + pence.format(snickers) 
                        + "\nT = Twix: " + pence.format(twix)
                        + "\n======================"
                        + "\n\n");
                    }
                }

            while (productName == null);        // End of validation loop when product selection is valid

            }               // End of class SelectItem


            /**
             * NotEnoughMoney method for when not enough money is inserted to purchase product
             */
            public void NotEnoughMoney()
            {           
                String spaymentSum2;        // Money inserted by user for parsing into Integer value
                int paymentSum2;        // Money inserted by customer parsed into Integer value as pence

                if (paymentSum == 0)        // Continuing s: select item operation
                    {
                        spaymentSum = (JOptionPane.showInputDialog(
                            "======================================"
                            + "\nTo buy " + productName 
                            + " you need to enter at least " + pence.format(price)
                            + "\n======================================"
                            + "\n\n"));         // Inserting money
                        paymentSum = Integer.parseInt(spaymentSum); // Parsing for calculations

                if (paymentSum < price) // If not enough money has been inserted
                    do      // start of not enough money entered loop
                        {
                        spaymentSum2 = JOptionPane.showInputDialog(
                            "=========================================="
                            + "\nYou have not entered enough to buy: " 
                            + productName + " at " + pence.format(price)
                            + "\n\nBalance: " + pence.format(paymentSum) 
                            + "\nRemaining: " + pence.format((price-paymentSum))
                            + "\n\nPlease insert more money (in pence) or q to quit: "
                            + "\n=========================================="
                            + "\n");
                        if ("q".equals(spaymentSum2))                   // If user quits
                            {
                            JOptionPane.showMessageDialog(null, 
                                "======================" 
                                + "\n" + pence.format(paymentSum) 
                                + " has been returned to you." 
                                + "\nThank you for your custom."
                                + "\n======================");
                            System.exit(0);
                            }
                        else
                                {
                                paymentSum2 = Integer.parseInt(spaymentSum2);   // Parsing additional funds added
                                paymentSum = paymentSum + paymentSum2;  // new total including additional funds
                                }
                        }

                    while (paymentSum < price);     // End of loop when enough money inserted

                changeLeft = paymentSum - price;        // Calculate change left after product purchase;

            }       // End of NotEnoughMoney method
        }


        /**
         * GiveChange constructor to output change left after product purchase in various denominations
         */

        public void GiveChange()
        {
            int fiver;      //variable for £5 note
            int £2pound;    //variable for £2 coin
            int £1pound;    //variable for £1 coin
            int p50;        //variable for 50p coin
            int p20;        //variable for 20p coin
            int p10;        //variable for 10p coin
            int p5;     //variable for 5p coin
            int p2;     //variable for 2p coin
            int p1;     //variable for 1p coin

            int changeCoins = changeLeft;       // new variable used for calculating change in demoninations

            // Calculating change for output in various denominations

            fiver = changeCoins/500;
            changeCoins = changeCoins%500;
            if (fiver < 0)                  
                fiver = 0;
            £2pound = changeCoins/200;
            changeCoins = changeCoins%200;
            if (£2pound < 0)
                £2pound = 0;
            £1pound = changeCoins/100;
            changeCoins = changeCoins%100;
            if (£1pound < 0)
                £1pound = 0;
            p50 = changeCoins/50;
            changeCoins = changeCoins%50;
            if (p50 < 0)
                p50 = 0;            
            p20 = changeCoins/20;
            changeCoins = changeCoins%20;
            if (p20 < 0)
                p20 = 0;            
            p10 = changeCoins/10;
            changeCoins = changeCoins%10;
            if (p10 < 0)
                p10 = 0;            
            p5 = changeCoins/5;
            changeCoins = changeCoins%5;
            if (p5 < 0)
                p5 = 0;         
            p2 = changeCoins/2;
            changeCoins = changeCoins%2;
            if (p2 < 0)
                p2 = 0;         
            p1 = changeCoins/1;

            // Output screen for displaying the change in various denominations
            JOptionPane.showMessageDialog(null, 
                "======================"
                + "\nYou have bought " + productName + " for " + pence.format(price)
                +"\n\nYour change is: " + pence.format(changeLeft) 
                + "\n\n£5 note(s):  \t\t" + fiver       //printing the number of £5 notes given as change
                + "\n£2 coin(s):  \t\t" + £2pound   //printing the number of £2 coins given as change
                + "\n£1 coin(s):  \t\t" + £1pound   //printing the number of £1 coins given as change
                + "\n50p coin(s): \t\t" + p50       //printing the number of 50p coins given as change
                + "\n20p coin(s):  \t\t" + p20      //printing the number of 20p coins given as change
                + "\n10p coin(s):  \t\t" + p10      //printing the number of 10p coins given as change
                + "\n5p coin(s):   \t\t" + p5       //printing the number of 5p coins given as change
                + "\n2p coin(s):   \t\t" + p2       //printing the number of 2p coins given as change
                + "\n1p coin:   \t\t" + p1
                + "\n======================");  //printing the number of 1p coins given as change

        }       // End of GiveChange constructor


        /**
         * Repeat constructor used to ask if user wishes to buy another item
         */
        public void Repeat()
        {

            // User request to repeat operation

            again = JOptionPane.showConfirmDialog (null, 
                "================================"
                + "\nWould you like to make another purchase?"
                + "\n================================");

        }       // End of Repeat constructor

}       // End of VendingMachine class

1 个答案:

答案 0 :(得分:1)

在NotEnoughMoney方法中,&#34; if(this.paymentSum == 0)&#34;应该在&#34; if(this.paymentSum&lt; this.price)&#34;之前关闭,但相反,前者包含后者。当我修复它时,它工作