简体   繁体   中英

Math Logic in Java for Lemonade Stand Game

I am writing the lemonade stand game in Java but I am having a bit of trouble trying to figure out the perfect recipe. I mean something like if weather is Sunny and temperature is greater than 85 the perfect recipe would be 8 lemons, 6 cups of sugar and 12 ice cubes per cup. I have most of the code done, except the math logic seems a little off. Please let me know how can I improve the code. I included all the code so you can get a better idea on how all the logic goes so far.

public static void main(String[] args) {

        ///declaration of variables
    int playAgain;
    int days, customers = 120;
        int CUPS_PITCHER = 14;
        double money = 20.00, earned = 0;
        double [] cupsPrice = {0.93, 1.65, 2.77}, lemonsPrice = {0.98, 2.05, 4.38}, sugarPrice = {0.74, 1.63, 3.31}, icePrice = {0.99, 2.01, 3.95};
        //inventory
        ///string input
        String cupsS = "", lemonsS = "", sugarS = "", iceS = "";

        //int input values 
        int cups = 0, lemons = 0, sugar = 0, ice = 0;

        //String for Pitcher
        double priceCup;
        int lemonsPitcher, sugarPitcher, iceCup;

        ////array for items options
        String [] cupsOptions = {"25","50","100"};
        String [] lemonsOptions = {"10","30","75"};
        String [] sugarOptions = {"8","20","48"};
        String [] iceOptions = {"100","250","500"};

        int temperature;
        String [] weather = {"Sunny","Hazy","Cloudy","Overcast","Rainny"};

        JOptionPane.showMessageDialog(null,"Welcome to our Lemonade Stand Game");
        days = getDays();

        ///set flag for loops 
        boolean ingredients, cupsFlag, lemonsFlag, sugarFlag, iceFlag;
        boolean [] flag = {false,false,false,false};

        NumberFormat defaultFormat = NumberFormat.getCurrencyInstance();

        String [] itemName = {"Cups","Lemons","Sugar","Ice Cubes"};
        String [][] itemOptions = {cupsOptions,lemonsOptions,sugarOptions,iceOptions};

        for(int i=1; i<=days; i++){

            /////random weather 
            Random rand = new Random();
            int randomWeather = rand.nextInt(5);

            //random temperature from 59 to 99
            temperature = rand.nextInt(99-59) + 59;
            int response = 0;
            ///loop while not play game 
            while(response != 1){
                String[] options = new String[] {"Buy", "Play Game", "Cancel"};
                response = JOptionPane.showOptionDialog(null, "You currently have " + defaultFormat.format(money) + "    Day " + i + "\nCups: " + cups + "       *** Lemons: " + lemons + "\nSugar: " + 
                        sugar + "     *** Ice: "+ice + "\nHigh Temperature: " + temperature + "\nWeather Forecast: " + weather[randomWeather], "Inventory",
                JOptionPane.DEFAULT_OPTION, JOptionPane.PLAIN_MESSAGE,
                null, options, options[0]); 

                ingredients = false;
                ///if buy ingredientes ** when they click buy 
                while(response == 0 && !ingredients){
                    String[] optionsBuy = new String[] {"Buy Cups", "Buy Lemons", "Buy Sugar", "Buy Ice","Back to Game"};
                    String line1 = "\n25 Cups: $" + cupsPrice[0] + "          10 Lemons: $" + lemonsPrice[0] 
                            + "          8 Cups of Sugar: $" + sugarPrice[0] + "          100 Ice Cubes: $"+icePrice[0];
                    String line2 = "\n50 Cups: $" + cupsPrice[1] + "          30 Lemons: $" + lemonsPrice[0] 
                            + "          20 Cups of Sugar: $" + sugarPrice[1] + "        250 Ice Cubes: $"+icePrice[1];
                    String line3 = "\n100 Cups: $" + cupsPrice[2] + "        75 Lemons: $" + lemonsPrice[2] 
                            + "         48 Cups of Sugar: $" + sugarPrice[2] + "        500 Ice Cubes: $"+icePrice[2];
                    int responsePurchase = JOptionPane.showOptionDialog(null, "You currently have " + defaultFormat.format(money) + "    Day " + i + line1 + line2 + line3 + "\nHigh Temperature: " + temperature + "\nWeather Forecast: " + weather[randomWeather], "Inventory",
                    JOptionPane.DEFAULT_OPTION, JOptionPane.PLAIN_MESSAGE,
                    null, optionsBuy, optionsBuy[0]);

                    double [][] priceOptions = {cupsPrice,lemonsPrice,sugarPrice,icePrice};
                    int [] qty = {0,0,0,0};
                    for(int j=0; j<4; j++){
                        if(responsePurchase == j)
                            qty[j] = buyItems(itemName[j],itemOptions[j],flag[j],money);
                            //money = money - itemPrice[j][0];
                        }

                    ///deduct money 
                    for(int k=0;k<4;k++){
                        for(int j=0;j<3;j++){
                            if(qty[k] == Integer.parseInt(itemOptions[k][j])){
                            money = money - priceOptions[k][j];
                            }
                        }

                    }
                    ////add items purchased
                    cups += qty[0];
                    lemons += qty[1];
                    sugar += qty[2];
                    ice += qty[3];

                    //System.out.println(itemOptions[0][1]);
                    /*
                    if(qty[0] == 25){
                        money = money - cupsPrice[0];
                    }
                    if(qty[0] == 50){
                        money = money - cupsPrice[1];
                    }
                    if(qty[0] == 100){
                        money = money - cupsPrice[2];
                    }

                    // buy lemons
                    cupsFlag = false;
                    if (responsePurchase == 0) {
                      int qty = buyItems("Cups",cupsOptions,cupsFlag,money);
                      if (qty != 0) {
                        cups += qty;
                      }
                    }

                    // buy lemons
                    lemonsFlag = false;
                    if (responsePurchase == 1) {
                      int qty = buyItems("Lemons",lemonsOptions,lemonsFlag,money);
                      if (qty != 0) {
                        lemons += qty;
                      }
                    }
                    */
                    ///go back to game when back to game click
                    if(responsePurchase == 4){
                        ingredients = true;
                    }
                }///end while buy ingredients
            }///end while buy

            JTextField fieldCup = new JTextField("0.25");
            JTextField fieldLemons = new JTextField("4");
            JTextField fieldSugar = new JTextField("4");
            JTextField fieldIce = new JTextField("4");

            Object[] fields = {"Price per Cup in Cents", fieldCup,"Lemons per Pitcher", fieldLemons,"Sugar per Pitcher", fieldSugar, "Ice per Cup", fieldIce};

            int responsePitcher = JOptionPane.showConfirmDialog(null,fields,"Price",JOptionPane.OK_CANCEL_OPTION);
            if(responsePitcher == JOptionPane.CANCEL_OPTION){
                    int stopGame = JOptionPane.showConfirmDialog(null,"Do you wish to cancel the game? All progress will be lost","",JOptionPane.YES_NO_OPTION);
                    if(stopGame == JOptionPane.YES_OPTION){
                        System.exit(0);
                    }
                }
            while(!validateDouble(fieldCup.getText()) || !validateInt(fieldLemons.getText()) || !validateInt(fieldSugar.getText()) || !validateInt(fieldIce.getText())){

                if(responsePitcher == JOptionPane.CANCEL_OPTION){
                    int stopGame = JOptionPane.showConfirmDialog(null,"Do you wish to cancel the game? All progress will be lost","",JOptionPane.YES_NO_OPTION);
                    if(stopGame == JOptionPane.YES_OPTION){
                        System.exit(0);
                    }
                }
                JOptionPane.showMessageDialog(null,"One of the inputs is incorrect! try Again","ERROR",JOptionPane.ERROR_MESSAGE);
                responsePitcher = JOptionPane.showConfirmDialog(null,fields,"Price",JOptionPane.OK_CANCEL_OPTION);
            }

            priceCup = Double.parseDouble(fieldCup.getText());
            lemonsPitcher = Integer.parseInt(fieldLemons.getText());
            sugarPitcher = Integer.parseInt(fieldSugar.getText());
            iceCup = Integer.parseInt(fieldIce.getText());

            for(int k=0; k<5; k++){
                if(weather[randomWeather].equals(weather[k])){
                    ////if weather is not sunny reduce possible customers  
                    if(!weather[randomWeather].equals(weather[0])){
                       customers = customers - (customers * k/15);
                    }
                }
            }
            //System.out.println(customers);///testing results 
            //System.out.println(fieldCup.getText());///testing results 


            System.out.println(customers);///testing results
            //showBar();

            ///perfect recepie
            if(temperature > 58){
                ///if sunny
                if(weather[randomWeather].equals(weather[0])){

                }
            }

            //too expensive or not right ingredients reduce possible customers 
            if(priceCup > 0.25){
                customers = customers - (customers * 10/100);///reduce customers by 10% 
            }
            if(lemonsPitcher > 7 || lemonsPitcher < 5){
                customers = customers - (customers * 10/100);///reduce customers by 10% 
            }
            if(sugarPitcher > 7 || sugarPitcher < 5){
                customers = customers - (customers * 10/100);///reduce customers by 10% 
            }
            if(iceCup > 10 || iceCup < 6){
                customers = customers - (customers * 15/100);///reduce customers by 15% 
            }


            ///determine max cups according to inventory 
            int maxCupsLemons = (lemons / lemonsPitcher) * CUPS_PITCHER;
            int maxCupsSugar = (sugar / sugarPitcher) * CUPS_PITCHER;
            int maxCupsIce = (ice / iceCup);
            int maxCupsp = cups;

            int [] maxCups = {maxCupsLemons, maxCupsSugar, maxCupsIce, maxCupsp};

            System.out.println(Arrays.toString(maxCups));

            int minValue = maxCups[0];  
            for(int m=0;m<maxCups.length;m++){  
                if(maxCups[m] < minValue){  
                    minValue = maxCups[m];  
                }
            }
            System.out.println(minValue);
            if(minValue < customers){
                customers = minValue;
            }  
            System.out.println(customers);///testing results
            ////profit 
            earned = priceCup * customers;
            money += earned;


            ///deduct inventory
            //14 cups per pitcher 
            int lemonsSpent = (customers / CUPS_PITCHER) * lemonsPitcher;
            int sugarSpent = (customers / CUPS_PITCHER) * sugarPitcher;

            lemons = lemons - lemonsSpent;
            sugar = sugar - sugarSpent;
            cups = cups - customers;


            JOptionPane.showMessageDialog(null,"Your profit for day " + i + " is " + defaultFormat.format(earned));


            /////reset variables for next day
            customers = 120;
            earned = 0;
            ice = 0;
        }


    //JOptionPane.showMessageDialog(null,days);

    }
}

I think your problem is on the pricing. Better leave it as 14 cups. Then generate the price per cup.

First, you should have a standard measure on how many cups of an ingredient will be in one pitcher. That way, you will have a basis.

Let's say. 8 lemons + 6 cups of sugar + 12 ice cubes = 1 pitcher

Multiply the cup price. 8 * 0.98 , etc. then add it to other ingredients price.

But, it will be better and easier if you will remove the pitcher from the price computation. Since you will sell it by cups.

I'll give you a tip in formulating a program's logic. Most of the time, the obvious way to do it is the easiest way. Put yourself in the position of the program, if you were the program, what will you do?

In improving your program's logic, check every thing your program does. Ask yourself, is it the most likely thing I will do?

If your program works, never fear to take risks. Try other ways, try other algorithms, and read. Then decide which of those will improve your work. Most of the time trying something new begets failure, but that's the bittersweet way of learning.

Happy coding!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM