How to validate a double field?

Asked

Viewed 1,781 times

1

Good afternoon guys, I’m not able to validate the field type value double

The field I cannot validate for the registration is the field valor.

Follows the class method to validate the data to register:

 public boolean verificaDados(CardapioBeans cardapio, String valor){         

    if(cardapio.getDescricao().equals("")){ 
        JOptionPane.showMessageDialog(null, "Campo Descrição nao pode ser vazio","Erro de preenchimento", 0, new ImageIcon("Imagens/cancelar.png"));
        return false;  
    }

    if(valor.equals("")){  
        JOptionPane.showMessageDialog(null, "Campo Valor não pode ser vazio","Erro de preenchimento", 0, new ImageIcon("Imagens/cancelar.png"));
        return false; 
    }  
    cardapioD.cadastrarCardapio(cardapio); 
    return true;  
}

Follows the method cadastrarCardapio:

public void cadastrarCardapio(CardapioBeans cardapio){
    try { 
        String SQLInsertion = "insert into cardapio(car_descricao, car_tipo, car_valor) "
            + "values(?,?,?);";

        PreparedStatement stm = Conexao.getConnetion().prepareStatement(SQLInsertion);
        stm.setString(1, cardapio.getDescricao()); 
        stm.setString(2, cardapio.getTipo());   
        stm.setDouble(3, cardapio.getValor());  

        stm.execute();  

        Conexao.getConnetion().commit(); 
        JOptionPane.showMessageDialog(null, "cadastrado com sucesso!","cadastro efetivado",1,new ImageIcon("Imagens/sucess.png"));

    } catch (SQLException ex) { 
        JOptionPane.showMessageDialog(null, "Impossivel cadastrar","Erro de SQL", 0, new ImageIcon("Imagens/cancelar.png"));
    }
}

Follow the Event B_CadastrarActionPerformed:

private void B_CadastrarActionPerformed(java.awt.event.ActionEvent evt) {                                            
    capturaBeans();
    // se for true entra no if
    if(cardapioC.verificaDados(cardapioB, TF_Valor.getText())){ 
        limparTudo();
        habilitaTudo(false); // campos desabilitados para digitar 
    }    
}                                           

Follow the method that captures screen data:

final CardapioBeans capturaBeans(){
    cardapioB.setCodigo(Integer.parseInt(TF_Codigo.getText())); 
    cardapioB.setDescricao(TA_Descricao.getText()); 
    cardapioB.setTipo(CB_Tipo.getSelectedItem().toString());
    cardapioB.setValor(Double.parseDouble(TF_Valor.getText()));

    return cardapioB; 
} 

Follow the error when I click the sign up button:

   run:
Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: empty String
    at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:1842)
    at sun.misc.FloatingDecimal.parseDouble(FloatingDecimal.java:110)
    at java.lang.Double.parseDouble(Double.java:538)
    at GUI.CardapioGUI.capturaBeans(CardapioGUI.java:387)
    at GUI.CardapioGUI.B_CadastrarActionPerformed(CardapioGUI.java:294)
    at GUI.CardapioGUI.access$400(CardapioGUI.java:10)
    at GUI.CardapioGUI$6.actionPerformed(CardapioGUI.java:118)
    at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2022)
    at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2346)
    at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402)
    at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)
    at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:252)
    at java.awt.Component.processMouseEvent(Component.java:6525)
    at javax.swing.JComponent.processMouseEvent(JComponent.java:3324)
    at java.awt.Component.processEvent(Component.java:6290)
    at java.awt.Container.processEvent(Container.java:2234)
    at java.awt.Component.dispatchEventImpl(Component.java:4881)
    at java.awt.Container.dispatchEventImpl(Container.java:2292)
    at java.awt.Component.dispatchEvent(Component.java:4703)
    at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4898)
    at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4533)
    at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4462)
    at java.awt.Container.dispatchEventImpl(Container.java:2278)
    at java.awt.Window.dispatchEventImpl(Window.java:2750)
    at java.awt.Component.dispatchEvent(Component.java:4703)
    at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:758)
    at java.awt.EventQueue.access$500(EventQueue.java:97)
    at java.awt.EventQueue$3.run(EventQueue.java:709)
    at java.awt.EventQueue$3.run(EventQueue.java:703)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:75)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:86)
    at java.awt.EventQueue$4.run(EventQueue.java:731)
    at java.awt.EventQueue$4.run(EventQueue.java:729)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:75)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:728)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201)
    at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)
CONSTRUÍDO COM SUCESSO (tempo total: 35 segundos)

Follows the code that validates if the user enters a string But I’m trying to do how to validate the value field that is double type, Imagine q the user clicked on register and forgot to fill the value field of double type. I can not implement, obg

    private void TF_ValorFocusLost(java.awt.event.FocusEvent evt) {                                   
    try{
        double verifica = Double.parseDouble(TF_Valor.getText().replace(',','.'));
        TF_Valor.setText(formatoDecimal.format(verifica).replace(',', '.')); 
    } 
    catch(NumberFormatException ex){
        JOptionPane.showMessageDialog(null, "Campo Valor Deve Conter Apenas Números","Erro de preenchimento", 0, new ImageIcon("Imagens/cancelar.png"));
        TF_Valor.setText("");
        TF_Valor.requestFocus(); 
    }
}                                  

Follows the Nullpointerexception error: which happens in the Cardapiogui and Cardapiocontroller class in the verified method()

import Beans.CardapioBeans;
import Controller.CardapioController;
import java.text.DecimalFormat;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;

public class CardapioGUI extends javax.swing.JInternalFrame {

    DefaultTableModel modelo;  
    CardapioController cardapioC;
    CardapioBeans cardapioB;
    DecimalFormat formatoDecimal;

    public CardapioGUI() { 
        initComponents();
        TF_Codigo.setEditable(false);  
        habilitaTudo(false);  
        modelo = (DefaultTableModel)Tabela.getModel(); 
        cardapioC = new CardapioController();
        cardapioB = new CardapioBeans(); 
        formatoDecimal = new DecimalFormat("0.00");
    }
    private void B_CadastrarActionPerformed(java.awt.event.ActionEvent evt) {                                            
        //capturaBeans();
        // se for true entra no if
        if(cardapioC.verificaDados(cardapioB, TF_Valor.getText())){ 
            capturaBeans();
            limparTudo();
            habilitaTudo(false); // campos desabilitados para digitar 
        }    
    }      

Cardapio controller :

public boolean verificaDados(CardapioBeans cardapio, String valor){         

    if(cardapio.getDescricao().equals("")){ 
        JOptionPane.showMessageDialog(null, "Campo Descrição nao pode ser vazio","Erro de preenchimento", 0, new ImageIcon("Imagens/cancelar.png"));
        return false;  
    }
    if(valor.equals("")){  
    JOptionPane.showMessageDialog(null, "Campo Valor não pode ser vazio","Erro de preenchimento", 0, new ImageIcon("Imagens/cancelar.png"));
    return false; 
}
try {
    Double.parseDouble(valor);
} catch (NumberFormatException e) {
    JOptionPane.showMessageDialog(null, "Campo Valor não é um número","Erro de preenchimento", 0, new ImageIcon("Imagens/cancelar.png"));
    return false;
}
cardapioD.cadastrarCardapio(cardapio); 
return true;  
}
  • The field carValor Do you accept null in the database? The method is cardapioB.setValor(Double) or cardapioB.setValor(double)? I mean, he uses double lower case letter or Double capital letter?

  • Ah, you should use the Try-with-Resources in his PreparedStatement. The way it is, if there’s one SQLException, it will not be closed properly. See more here.

  • If it’s monetary value, you can start by not using double since this is an error. http://answall.com/q/77746/101

  • Much of this validation could have been eliminated using Jformattedtextfield. The end user experience is also much better since the feedback is immediate (it doesn’t need to submit the form). You can use your DecimalFormat (with setParseBigDecimal(true) see bigown advice) and a standard value (e.g., 0.00) to initialize the JFormattedTextField. With this the value will never be empty, will always be valid and you can recover the desired type (BigDecimal, Double, etc) with getValue().

3 answers

1

Try to change that:

    if(valor.equals("")){  
        JOptionPane.showMessageDialog(null, "Campo Valor não pode ser vazio","Erro de preenchimento", 0, new ImageIcon("Imagens/cancelar.png"));
        return false; 
    }

That’s why:

    if (valor.isEmpty()) {
        JOptionPane.showMessageDialog(null, "O campo Valor não pode ser vazio.", "Erro de preenchimento", 0, new ImageIcon("Imagens/cancelar.png"));
        return false; 
    }

    try {
        Double.parseDouble(valor);
    } catch (NumberFormatException e) {
        JOptionPane.showMessageDialog(null, "O campo Valor deve ser preenchido com um número.", "Erro de preenchimento", 0, new ImageIcon("Imagens/cancelar.png"));
        return false; 
    }

Or else, following Maniero’s suggestion, use BigDecimal:

    BigDecimal valorNumerico;
    try {
        valorNumerico = new BigDecimal(valor);
    } catch (NumberFormatException e) {
        JOptionPane.showMessageDialog(null, "O campo Valor deve ser preenchido com um número.", "Erro de preenchimento", 0, new ImageIcon("Imagens/cancelar.png"));
        return false; 
    }

In his method capturaBeans() you do something like this by displaying the error message and/or doing the corresponding validation.

  • Failed, the same error appears: Exception in thread "AWT-Eventqueue-0" java.lang.Numberformatexception: Empty String . How to handle this 'capture' bug()' /

0

It is no use just checking if the value is empty; the correct is to check if the String sent is actually a number. In your role verificaDados():

Alter:

if(valor.equals("")) {  
    JOptionPane.showMessageDialog(null, "Campo Valor não pode ser vazio","Erro de preenchimento", 0, new ImageIcon("Imagens/cancelar.png"));
    return false; 
}

For:

try {
    Double.parseDouble(valor);
} catch (NumberFormatException e) {
    JOptionPane.showMessageDialog(...);
}
  • The method check whether it is String or not I already have. But when the value is empty it shows the error q that is in the question

0

The problem is in this part:

private void B_CadastrarActionPerformed(java.awt.event.ActionEvent evt) {                                            
    capturaBeans();
    // se for true entra no if
    if(cardapioC.verificaDados(cardapioB, TF_Valor.getText())){ 
        limparTudo();
        habilitaTudo(false); // campos desabilitados para digitar 
    }    
}

You are ordering him to capture the values (no capturaBeans()) and then check if they are valid (with the cardapioC.verificaDados(cardapioB, TF_Valor.getText())).

Change your method so it only captures the values after validating them:

private void B_CadastrarActionPerformed(java.awt.event.ActionEvent evt) {                                            
    // se for true entra no if
    if(cardapioC.verificaDados(cardapioB, TF_Valor.getText())){ 
        capturaBeans();
        limparTudo();
        habilitaTudo(false); // campos desabilitados para digitar 
    }    
}

In addition, you must validate your String really is a double in his method verificaDados(CardapioBeans cardapio, String valor) :

public boolean verificaDados(CardapioBeans cardapio, String valor){         

    if(cardapio.getDescricao().equals("")){ 
        JOptionPane.showMessageDialog(null, "Campo Descrição nao pode ser vazio","Erro de preenchimento", 0, new ImageIcon("Imagens/cancelar.png"));
        return false;  
    }

    if(valor.equals("")){  
        JOptionPane.showMessageDialog(null, "Campo Valor não pode ser vazio","Erro de preenchimento", 0, new ImageIcon("Imagens/cancelar.png"));
        return false; 
    }
    try {
        Double.parseDouble(valor);
    } catch (NumberFormatException e) {
        JOptionPane.showMessageDialog(null, "Campo Valor não é um número","Erro de preenchimento", 0, new ImageIcon("Imagens/cancelar.png"));
        return false;
    }
    cardapioD.cadastrarCardapio(cardapio); 
    return true;  

}

  • Does not work, gives a java.lang.Nullpointerexception on line 20

  • @Jose.Lemo can show the stack trace of the NullPointerException and the complete class from which it is launched?

  • Yes. In class Cardapiogui (Row 10) in class Cardapiocontroller in method checked row 20 (in first if). I will edit to put these classes

Browser other questions tagged

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