String to Double - Help!

1

I'm trying to add a column to a JTable. Any suggestions on how to do it?

public void actionPerformed(ActionEvent arg0) {
                try {
                    double itens = 0;
                    double soma = 0;

                    for (int i = 0; i < jtbRacao.getColumnCount(); i++) {
                        itens = Double.valueOf((String) jtbRacao.getValueAt(i, 3));
                        soma += itens;
                    }
                    lblPB.setText(String.valueOf(soma));
                } catch (Exception e) {
                    JOptionPane.showMessageDialog(null, "Erro ao calcular Total Produtos: " + e.getMessage());
                }
            }

Stacktrace

WedJul1916:33:17BRT2017WARN:EstablishingSSLconnectionwithoutserver'sidentityverificationisnotrecommended.AccordingtoMySQL5.5.45+,5.6.26+and5.7.6+requirementsSSLconnectionmustbeestablishedbydefaultifexplicitoptionisn'tset.ForcompliancewithexistingapplicationsnotusingSSLtheverifyServerCertificatepropertyissetto'false'.YouneedeithertoexplicitlydisableSSLbysettinguseSSL=false,orsetuseSSL=trueandprovidetruststoreforservercertificateverification.WedJul1916:33:20BRT2017WARN:EstablishingSSLconnectionwithoutserver'sidentityverificationisnotrecommended.AccordingtoMySQL5.5.45+,5.6.26+and5.7.6+requirementsSSLconnectionmustbeestablishedbydefaultifexplicitoptionisn'tset.ForcompliancewithexistingapplicationsnotusingSSLtheverifyServerCertificatepropertyissetto'false'.YouneedeithertoexplicitlydisableSSLbysettinguseSSL=false,orsetuseSSL=trueandprovidetruststoreforservercertificateverification.WedJul1916:33:20BRT2017WARN:EstablishingSSLconnectionwithoutserver'sidentityverificationisnotrecommended.AccordingtoMySQL5.5.45+,5.6.26+and5.7.6+requirementsSSLconnectionmustbeestablishedbydefaultifexplicitoptionisn'tset.ForcompliancewithexistingapplicationsnotusingSSLtheverifyServerCertificatepropertyissetto'false'.YouneedeithertoexplicitlydisableSSLbysettinguseSSL=false,orsetuseSSL=trueandprovidetruststoreforservercertificateverification.WedJul1916:33:23BRT2017WARN:EstablishingSSLconnectionwithoutserver'sidentityverificationisnotrecommended.AccordingtoMySQL5.5.45+,5.6.26+and5.7.6+requirementsSSLconnectionmustbeestablishedbydefaultifexplicitoptionisn'tset.ForcompliancewithexistingapplicationsnotusingSSLtheverifyServerCertificatepropertyissetto'false'.YouneedeithertoexplicitlydisableSSLbysettinguseSSL=false,orsetuseSSL=trueandprovidetruststoreforservercertificateverification.WedJul1916:33:23BRT2017WARN:EstablishingSSLconnectionwithoutserver'sidentityverificationisnotrecommended.AccordingtoMySQL5.5.45+,5.6.26+and5.7.6+requirementsSSLconnectionmustbeestablishedbydefaultifexplicitoptionisn'tset.ForcompliancewithexistingapplicationsnotusingSSLtheverifyServerCertificatepropertyissetto'false'.YouneedeithertoexplicitlydisableSSLbysettinguseSSL=false,orsetuseSSL=trueandprovidetruststoreforservercertificateverification.Exceptioninthread"AWT-EventQueue-0" java.lang.NumberFormatException: For input string: "3,58"
    at sun.misc.FloatingDecimal.readJavaFormatString(Unknown Source)
    at sun.misc.FloatingDecimal.parseDouble(Unknown Source)
    at java.lang.Double.parseDouble(Unknown Source)
    at java.lang.Double.valueOf(Unknown Source)
    at VIEW.TelaRacao$7.actionPerformed(TelaRacao.java:313)
    at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
    at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
    at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
    at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
    at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source)
    at java.awt.Component.processMouseEvent(Unknown Source)
    at javax.swing.JComponent.processMouseEvent(Unknown Source)
    at java.awt.Component.processEvent(Unknown Source)
    at java.awt.Container.processEvent(Unknown Source)
    at java.awt.Component.dispatchEventImpl(Unknown Source)
    at java.awt.Container.dispatchEventImpl(Unknown Source)
    at java.awt.Component.dispatchEvent(Unknown Source)
    at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
    at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
    at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
    at java.awt.Container.dispatchEventImpl(Unknown Source)
    at java.awt.Window.dispatchEventImpl(Unknown Source)
    at java.awt.Component.dispatchEvent(Unknown Source)
    at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
    at java.awt.EventQueue.access$500(Unknown Source)
    at java.awt.EventQueue$3.run(Unknown Source)
    at java.awt.EventQueue$3.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
    at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
    at java.awt.EventQueue$4.run(Unknown Source)
    at java.awt.EventQueue$4.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
    at java.awt.EventQueue.dispatchEvent(Unknown Source)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
    at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    at java.awt.EventDispatchThread.run(Unknown Source)
    
asked by anonymous 19.07.2017 / 20:46

2 answers

3

Some points I've seen here:

  • On the screen, the column should be showing decimal places with "," instead of ".", which is expected by the Double.parseDouble() method. Use the java.text.NumberFormat class to convert and format values from and to localized strings.
  • In the for loop, you are going from 0 to columns , you should actually go up to the number of lines .
  • To sum values and other operations that require precision, it is not good to use either float or double , because they are floating points. It's more interesting to use the java.math.BigDecimal class.
  • Looking at this, it would look like this:

    public void actionPerformed(ActionEvent arg0) {
        try {
            BigDecimal soma = BigDecimal.ZERO;
            // pega o formato de número para o "locale" atual
            NumberFormat nf = NumberFormat.getNumberInstance();
    
            // varre todas as LINHAS da tabela, coluna 3
            for (int i = 0; i < jtbRacao.getRowCount(); i++) {
                String coluna = jtbRacao.getValueAt(i, 3).toString();
                // converte de string para number
                Number valor = nf.parse(coluna);
                // soma com o total atual. BigDecimal sempre retorna uma instância nova, então precisa atualizar a variável
                soma = soma.add(new BigDecimal(valor.toString()));
            }
            // formata a soma para exibir no label
            lblPB.setText(nf.format(soma));
        } catch (Exception e) {
            JOptionPane.showMessageDialog(null, "Erro ao calcular Total Produtos: " + e.getMessage());
            // não esqueça de escrever a exceção no log...
            e.printStackTrace();
        }
    }
    
        
    19.07.2017 / 22:13
    1

    Apparently your problem should be in converting String value to Double, try to make a comma replace to point.

    Ex:

    String valor = "9,99"
    valor = valor.replace(",", ".");
    Double valorDouble = Double.parseDouble(valor);
    
        
    19.07.2017 / 21:09