Numberformatexception in GUI

Asked

Viewed 138 times

0

I have a program that simulates a pizzeria system, where the prices of the products are stored in enums as double. The JLabel from the window take these price values and present it on the screen in this way : "R$ "+ p.getValue;. Where the p.getValue is the price. I took this string and put inside a double variable (using the .substring(3);). I perform the sum of these variables and "game" into the text of a JTextField, until then everything happened normal, only when I apply a DecimalFormat to show two decimal places(df.applyPattern(##.##)), and run, it applies this pattern, only on the console appears "Numberformatexception: For input String :"37.49".

Method where I get the price (.getValue) of the Enum (double) item, as I change an item in a JComboBox:

form.cmbPizza.addItemListener(new ItemListener() {  
            @Override
            public void itemStateChanged(ItemEvent e) {
                if(e.getStateChange() == ItemEvent.SELECTED){
                    Pizzas p = (Pizzas) e.getItem();
                    form.lblPrecoPizza.setText("R$ "+p.getValue());
                }else{
                    form.lblPrecoPizza.setText("R$ 0.00");
                }
            }
        });

Method that performs formatting and conversions :

form.btnCalcular.addActionListener(new ActionListener() { //Apresentar soma dos produtos

        @Override
        public void actionPerformed(ActionEvent arg0) {
            form.precoPizza = Double.parseDouble(form.lblPrecoPizza.getText().substring(3));
            form.precoSuco = Double.parseDouble(form.lblPrecoSuco.getText().substring(3));
            form.precoRefri = Double.parseDouble(form.lblPrecoRefri.getText().substring(3));

            df.applyPattern("##.##");
            form.txtPrecoTotal.setText(String.valueOf(df.format(form.precoPizza + form.precoSuco + form.precoRefri)));
            double x = Double.parseDouble(form.txtPrecoTotal.getText()); //Linha onde é acusado o erro
            df.format(x);
            if(form.chkVip.isSelected()){
                double desconto = (form.precoPizza + form.precoRefri + form.precoSuco)*0.15;
                form.txtPrecoTotal.setText(df.format(String.valueOf(form.precoPizza + form.precoSuco + form.precoRefri - desconto)));
            }

        }
    });

Making it clear once again that this is a Runtime error, not a compilation error and that the error occurs not only with this value, but with any value !

  • Where does this comma come from between 37 and 49? English numbers are separated by dots.

  • Add the full stacktrace, showing where exactly you’re bursting this exception. But I can tell you that if you’re using the values of ENUM according to the code of your other question, the problem may be in these commas, double separator and float is dot(.). Try switching directly in ENUM to see if the error persists.

  • So dude, my program doesn’t have a comma number, just a period, my teacher said that on the console the number appears comma by which the IDE at the time it launches the error, it sees what the separation pattern of your country and applies them to your number ...

  • Daniel, yes, in your ENUM the numbers are comma, at least in the code you posted in the other question. When you do p.getValue(), comes the values of ENUM as stated, ie with comma. Try to do as I said, change the ENUM commas per point in the prices and see if the error persists.

  • Diego, the enums are already changed with dot, replace all the commas that existed in the code, and continue giving the same error

  • Then add in the question the stack of errors that appear in the console, can not guess the origin of the error without seeing the message.

Show 1 more comment

1 answer

1


Daniel, to treat values instead of using R$ hardcode, you can use the class NumberFormat, using a utility method such as:

// Adicione esses atributos à sua classe
private Locale localeBrasil = new Locale("pt", "BR");
private NumberFormat formatoMonetario = NumberFormat.getCurrencyInstance(localeBrasil);

// Método utilitário
public double parseValor(String str) {
    Number valor = 0;

    try {
        valor = formatoMonetario.parse(str);
    } catch (ParseException e) {
    }

    return valor.doubleValue();
}

Replacing where you recover the value:

form.precoPizza = Double.parseDouble(form.lblPrecoPizza.getText().substring(3));

For:

form.precoPizza = parseValor(form.lblPrecoPizza.getText());

And where you set the value:

form.lblPrecoPizza.setText("R$ "+ p.getValue());

for:

form.lblPrecoPizza.setText(formatoMonetario.format(p.getValue()));

Leaving something like this:

form.cmbPizza.addItemListener(new ItemListener() {  
            @Override
            public void itemStateChanged(ItemEvent e) {
                if(e.getStateChange() == ItemEvent.SELECTED){
                    Pizzas p = (Pizzas) e.getItem();
                    form.lblPrecoPizza.setText(formatoMonetario.format(p.getValue()));
                }else{
                    form.lblPrecoPizza.setText(formatoMonetario.format(0));
                }
            }
        });


form.btnCalcular.addActionListener(new ActionListener() { //Apresentar soma dos produtos

        @Override
        public void actionPerformed(ActionEvent arg0) {
            form.precoPizza = parseValor(form.lblPrecoPizza.getText());
            form.precoSuco = parseValor(form.lblPrecoSuco.getText());
            form.precoRefri = parseValor(form.lblPrecoRefri.getText());

            form.txtPrecoTotal.setText(formatoMonetario.format(form.precoPizza + form.precoSuco + form.precoRefri));
            double x = parseValor(form.txtPrecoTotal.getText());

            if(form.chkVip.isSelected()){
                double desconto = (form.precoPizza + form.precoRefri + form.precoSuco)*0.15;
                form.txtPrecoTotal.setText(formatoMonetario.format(form.precoPizza + form.precoSuco + form.precoRefri - desconto));
            }
        }
    });

Abcs!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.