How to validate a field of type double?

1

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

The field that I can not validate for the cadaster is the valor field.

Follow 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;  
}

The cadastrarCardapio method follows:

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 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 
    }    
}                                           

The method that captures screen data follows:

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; 
} 

The error follows when I click on the button to register:

   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)

The code that validates if the user enters a string But I am trying to do as validate the value field which is of type double, Imagine q the user clicked on register and forgot to fill the value field of type double. I'm not able to 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(); 
    }
}                                  

The NullPointerException error follows: which happens in the class CardapioGUI and CardapioController in the method verified ()

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;  
}
    
asked by anonymous 23.01.2017 / 16:14

3 answers

1

Try changing this:

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

So:

    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, following the bigown hint, 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 your capturaBeans() method you do something like this by displaying the error message and / or doing the corresponding validation.

    
23.01.2017 / 16:29
0

It's no use just checking if the value is empty; the correct thing is to check if the String sent is actually a number. In its verificaDados() function:

Change:

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

By:

try {
    Double.parseDouble(valor);
} catch (NumberFormatException e) {
    JOptionPane.showMessageDialog(...);
}
    
23.01.2017 / 16:27
0

The problem lies 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 telling him to capture the values (in capturaBeans() ) and then check if they are valid (with 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 should validate if your String is actually a double in your verificaDados(CardapioBeans cardapio, String valor) method:

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;  

}

    
23.01.2017 / 16:37