Stopping a while loop

0

I'm developing a system with JFrame from a pharmacy. It's a matter of faculty. In the box operator enters the quantity X of product that the customer chooses from a list of n products and then with the unit value of each product that is worth Y. At the end the system must show the total value of the purchase by multiplying X * Y =?. This code is simple to make and use the terminal or do it without problems. An example of how I control the loop through the terminal.

while (n == 0){
        System.out.printf("\nEscolha:\n\t1 - Inserir novo produto\n\t0 - Valor Total");
            k = input.nextInt();
            if(k == 1){
                System.out.println("Quantidade de produtos: ");
                    //recebe
                System.out.println("Valor unitário");
                    //recebe
                    valorFinal = valorFinal + (quantidade * valorUnitario);
            }
            if(k == 0){
                //qualquer coisa
                n++;
                //interrompe o laço e imprime o valor
            }
    }

Using JFrame it does not work like this, since it does not have the user to choose option 1 or 0. In this case I thought about creating a button [Add Product] and every time it was clicked the seller would add the products and the unit value and when it clicked on the [End Value] button the loop would be interrupted and the result would be shown.

int n = 0;
    double valorFinal = 0;

    while(n == 0){
        resposta = JOptionPane.showConfirmDialog(null, "Cadastrar nova compra?");
        if(resposta == JOptionPane.YES_OPTION){
            double qtdIten = Double.valueOf(jTextField1.getText());
            double valor = Double.valueOf(jTextField2.getText());

             valorFinal = (valorFinal + (valor * qtdIten));

        }
        else{
            jTextArea1.setText("Valor da compra: "+valorFinal);
            n++;
        }
    }

In a very amateurish way I made this attempt with a JOptionPane but it did not work.

    
asked by anonymous 17.04.2018 / 18:00

1 answer

2

I guess what's not working is that JOptionPane is over the screen and you can not go back to enter new values.

Ideally you would do the following when the user clicks the add button you get the values (as you did within if same) and sum, then you assign "" to the text fields to clear the fields. Instead of clicking the OK of JOptionPane several times click the add button several times.

You can even have a field on the screen where you are already writing the current ending value.

Another way would be to use JOptionPane.showInputDialog that shows a text field, so the user could enter the values of X and Y directly in the dialog. It is not exactly professional, but it would allow data entry. You could do this with a single command JOptionPane.showInputDialog and values separated by a comma, or call JOptionPane.showInputDialog twice, one for each value you want to capture.

    
17.04.2018 / 18:11