0

Soy estudiante, estoy haciendo una maquina espendedora, casi la termino, pero estoy teniendo problemas cuando mi stock de monedas es cero, en teoria tendria que salir un mensaje diciendo que no puede dar cambio pero da el cambio igual y no lo descuenta del stock. Necesito encontrar la logica para cuando dar un mensaje cuando no tengo suficiente monedas para dar cambio.

Les dejo mi codigo aqui, esto es cuando pagas:

//Payments
String selectedPayment = "";

//notes and coins values
public static double[] coinsAndNotes = new double[]{0.1, 0.2, 0.5, 1.0, 2.0, 5.0, 10.0, 20.0};

//counters of the money in
public static int[] counterMoneyIn = new int[]{0, 0, 0, 0, 0, 0, 0, 0};

// Total of money
double totalMoneyInMachine = (Stock.stockCoins[0] * coinsAndNotes[0]) + (Stock.stockCoins[1] * coinsAndNotes[1])
        + (Stock.stockCoins[2] * coinsAndNotes[2]) + (Stock.stockCoins[3] * coinsAndNotes[3]) + (Stock.stockCoins[4] * coinsAndNotes[4])
        + (Stock.stockNotes[0] * coinsAndNotes[5]) + (Stock.stockNotes[1] * coinsAndNotes[6]) + (Stock.stockNotes[2] * coinsAndNotes[7]);

double TotalMoneyInserted = (Stock.stockCoins[0] * counterMoneyIn[0]) + (Stock.stockCoins[1] * counterMoneyIn[1])
        + (Stock.stockCoins[2] * counterMoneyIn[2]) + (Stock.stockCoins[3] * counterMoneyIn[3]) + (Stock.stockCoins[4] * counterMoneyIn[4])
        + (Stock.stockNotes[0] * counterMoneyIn[5]) + (Stock.stockNotes[1] * counterMoneyIn[6]) + (Stock.stockNotes[2] * counterMoneyIn[7]);

private void jButtonPayActionPerformed(java.awt.event.ActionEvent evt) {                                           

    double change = 0.0;
    DecimalFormat df = new DecimalFormat("0.00");

    PaymentMethod pm = new PaymentMethod();

    change = TotalMoneyInserted - VMachine.price;


    if (TotalMoneyInserted < VMachine.price) {
        change *= -1;
        JOptionPane.showMessageDialog(null, "Sorry, not enough money, please enter" + " " + "€" + df.format(change) + " " + "more", "Insufficent Funds", JOptionPane.ERROR_MESSAGE);
      } else if (totalMoneyInMachine < change) {

        JOptionPane.showMessageDialog(null, "Sorry, There is not enough change in the machine, try to insert less money", "Change Insufficient", JOptionPane.ERROR_MESSAGE);

        //ten cent
        Stock.stockCoins[0] += -counterMoneyIn[0];
        //twenty cent
        Stock.stockCoins[1] += -counterMoneyIn[1];
        //fifty cent
        Stock.stockCoins[2] += -counterMoneyIn[2];
        //one euro
        Stock.stockCoins[3] += -counterMoneyIn[3];
        //two euros
        Stock.stockCoins[4] += -counterMoneyIn[4];
        //five note
        Stock.stockNotes[0] += -counterMoneyIn[5];
        //ten note
        Stock.stockNotes[1] += -counterMoneyIn[6];
        //twenty note
        Stock.stockNotes[2] += -counterMoneyIn[7];

        pm.setVisible(true);
        setVisible(false);

    } else {


        while (change > 0.01) {

            if (change >= 20) {
                change = roundAndReduce(change, 20);
                if (Stock.stockNotes[2] > 0) {
                    Stock.stockNotes[2]--;
                } else {
                    System.out.println("we don't have 20 to complete the operation");
                    pm.setVisible(true);
                    setVisible(false);
                }
            } else if (change >= 10) {
                change = roundAndReduce(change, 10);
                if (Stock.stockNotes[1] > 0) {
                    Stock.stockNotes[1]--;
                } else {
                    System.out.println("we don't have 10 to complete the operation");
                    pm.setVisible(true);
                    setVisible(false);
                }
            } else if (change >= 5) {
                change = roundAndReduce(change, 5);
                if (Stock.stockNotes[0] > 0) {
                    Stock.stockNotes[0]--;
                } else {
                    System.out.println("we don't have 5 to complete the operation");
                    pm.setVisible(true);
                    setVisible(false);
                }
            } else if (change >= 2) {
                change = roundAndReduce(change, 2);
                if (Stock.stockCoins[4] > 0) {
                    Stock.stockCoins[4]--;
                } else {
                    System.out.println("we don't have 2 to complete the operation");
                    pm.setVisible(true);
                    setVisible(false);
                }
            } else if (change >= 1) {
                change = roundAndReduce(change, 1);
                if (Stock.stockCoins[3] > 0) {
                    Stock.stockCoins[3]--;
                } else {
                    System.out.println("we don't have 1 to complete the operation");
                    pm.setVisible(true);
                    setVisible(false);
                }
            } else if (change >= 0.5) {
                change = roundAndReduce(change, 0.5);
                if (Stock.stockCoins[2] > 0) {
                    Stock.stockCoins[2]--;
                } else {
                    System.out.println("we don't have 0.5 to complete the operation");
                    pm.setVisible(true);
                    setVisible(false);
                }
            } else if (change >= 0.2) {
                change = roundAndReduce(change, 0.2);
                if (Stock.stockCoins[1] > 0) {
                    Stock.stockCoins[1]--;
                } else {
                    System.out.println("we don't have 0.2 to complete the operation");
                    pm.setVisible(true);
                    setVisible(false);
                }
            } else if (change >= 0.1) {
                change = roundAndReduce(change, 0.1);
                if (Stock.stockCoins[0] > 0) {
                    Stock.stockCoins[0]--;

                } else {
                    System.out.println("we don't have 0.1 to complete the operation");
                    pm.setVisible(true);
                    setVisible(false);
                }
            }

        }
       change = TotalMoneyInserted - VMachine.price;

        JOptionPane.showMessageDialog(null, "Your Change is: €" + df.format(change));
        ResetArrayCounter();
        mainMenu(this);

    }


}

roundAndReduce(double change, double reduction) { change -= reduction; 
change = (double) Math.round(change * 100) / 100; return change; } } 

Muchas gracias por la ayuda!


Creo que estoy cerca de solucionar este problema, pero estoy con un loop infinito, sacando eso, creo que funcionaria. Se los dejo para que den sus opiniones. Gracias!

 while (change > 0.01) {

            if (change >= 20 && Stock.stockNotes[2] > 0) {


                    change = roundAndReduce(change, 20);
                    Stock.stockNotes[2]--;
                 }else if (change >= 10 && Stock.stockNotes[1] > 0) {

                        change = roundAndReduce(change, 10);
                        Stock.stockNotes[1]--;

                } else if (change >= 5 && Stock.stockNotes[0] > 0) {
                        change = roundAndReduce(change, 5);
                        Stock.stockNotes[0]--;

                } else if (change >= 2 && Stock.stockCoins[4] > 0) {


                        change = roundAndReduce(change, 2);
                        Stock.stockCoins[4]--;

                }
            else if (change >= 1 && Stock.stockCoins[3] > 0) {


                    change = roundAndReduce(change, 1);
                    Stock.stockCoins[3]--;

            } else if (change >= 0.5 && Stock.stockCoins[2] > 0) {


                    change = roundAndReduce(change, 0.5);
                    Stock.stockCoins[2]--;

            } else if (change >= 0.2 && Stock.stockCoins[1] > 0) {


                    change = roundAndReduce(change, 0.2);
                    Stock.stockCoins[1]--;

            } else if (change >= 0.1 && Stock.stockCoins[0] > 0) {


                    change = roundAndReduce(change, 0.1);
                    Stock.stockCoins[0]--;

                }
            JOptionPane.showMessageDialog(null, "Sorry, There is not enough change in the machine, insert exact change", "Out of Change", JOptionPane.ERROR_MESSAGE);


        }
7
  • que hace roundAndReduce? porque la logica de controlar si puede dar cambio deberia estar ahi.. porque si no, da el cambio igual, porque no controla que haya de ese tipo, ya que el control, lo estas haciendo despues! Aparte, si se queda sin cambio, donde esta ese control?
    – gbianchi
    el 7 dic. 2018 a las 13:27
  • @gbianchi esto hace roundAndReduce: public static double roundAndReduce(double change, double reduction) { change -= reduction; change = (double) Math.round(change * 100) / 100; return change; } }
    – Chris
    el 7 dic. 2018 a las 16:59
  • 1
    fijate si esto no te da una mejor idea: es.stackoverflow.com/q/217691/324
    – gbianchi
    el 7 dic. 2018 a las 17:02
  • y pon el codigo en la pregunta..
    – gbianchi
    el 7 dic. 2018 a las 17:03
  • Sugerencia para claridad: defini constantes int para los subindices de cada denominación de dinero y usalo en los arrays. Ej. public static final int CENT = 0;
    – Juan
    el 7 dic. 2018 a las 17:43

1 respuesta 1

1

Éste problema lo he visto muchas veces hasta yo mismo he cometido el error. Las variables tipo double son utiles hasta cierto punto, el double a veces no guarda bien tus decimales y cuando los vas a comparar, no te va a reconocer la condicional por esto mismo.

Veo que también haces redondeos en estos, peor aún, ya que en algún punto puede que no te guarde adecuadamente estos.

La solución que puedes usar es la clase BigDecimal, la cual está adecuada para trabajar con decimales exactos con operaciones que dependen de ti y que función casi exactamente igual que el tipo de dato double, pero como es una clase,trae método muy útiles como el BigDecimal.Round que te permite redondear el numero al numero mas cercano, al numero de arriba, al de abajo y hasta dejándote decidir cuantos decimales quieres que se redondeen.

Te la recomiendo, es muy útil y estoy seguro que revolverá tu problema.

1
  • Por cierto, en la realidad el dinero se maneja con variables tipo BigDecimal, para que lo tengas en cuenta. el 11 dic. 2018 a las 14:17

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge you have read our privacy policy.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.