1

Estou tentando somar uma coluna de um JTable. Alguma sugestão de como fazer?

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

inserir a descrição da imagem aqui inserir a descrição da imagem aqui


Stack trace

Wed Jul 19 16:33:17 BRT 2017 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
Wed Jul 19 16:33:20 BRT 2017 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
Wed Jul 19 16:33:20 BRT 2017 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
Wed Jul 19 16:33:23 BRT 2017 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
Wed Jul 19 16:33:23 BRT 2017 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
Exception in thread "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)
14
  • Troca a vírgula da string por ponto. 19/07/2017 às 18:48
  • Erro ao Calcular Total Produtos: 2 >= 2 19/07/2017 às 18:50
  • Esqueci de avisar que já havia tentado com inteiro e retornou esse erro. 19/07/2017 às 18:51
  • 1
    Não mascare o erro com esse catch, deixa a exceção estourar e cole a pilha de erros aqui.
    – user28595
    19/07/2017 às 19:03
  • 1
    Douglas, descobri...na verdade eram dois erros: o que vc indicou sobre a troca da vírgula pelo ponto e o outro era o getColumnCount q na verdade o correto é getRowCount...deu certo! 19/07/2017 às 20:21

2 Respostas 2

3

Alguns pontos que vi aqui:

  1. Na tela, a coluna deve estar mostrando casas decimais com "," ao invés de ".", que é o esperado pelo método Double.parseDouble(). Use a classe java.text.NumberFormat para converter e formatar valores de e para strings localizadas.
  2. No laço for, você está indo de 0 até o número de colunas, deve ir na verdade até o número de linhas.
  3. Para somar valores e outras operações que necessitam de precisão, não é bom usar nem float nem double, por serem pontos flutuantes. É mais interessante usar a classe java.math.BigDecimal.

Observando isso, ficaria assim:

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();
    }
}
1

Aparentemente o seu problema deve ser na conversão de valor String para o Double, tenta fazer um replace de virgula para ponto.

Ex:

String valor = "9,99"
valor = valor.replace(",", ".");
Double valorDouble = Double.parseDouble(valor);
1
  • Felipe, tentei sua sugestão mas infelizmente não deu certo... 19/07/2017 às 19:27

Você deve fazer log-in para responder a esta pergunta.

Esta não é a resposta que você está procurando? Pesquise outras perguntas com a tag .