I have a program that simulates a pizzeria system where product prices are stored in enums as a double. The% window% takes these price values and displays it on the screen in this way: JLabel
. Where "R$ "+ p.getValue;
is the price. I got this String and put it inside a double variable (using p.getValue
). I make the sum of these variables and "game" into the text of a .substring(3);
, until everything has been normal, but when I apply a JTextField
to show two decimal places ( DecimalFormat
, and execute, it applies this pattern, only in the console appears "NumberFormatException: For input String:" 37.49 ".
Method where I get the price ( df.applyPattern(##.##))
) of the enum (double) item, as I change item in .getValue
:
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 the formatting and conversion:
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 that this is a runtime error, not a compilation error, and that the error does not only occur with this value, but with any value!