String for Double - Help!

Asked

Viewed 209 times

1

I’m trying to add a column of a Jtable. Any suggestions on how to do?

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)
  • Swap string comma by period.

  • Error When Calculating Total Products: 2 >= 2

  • I forgot to tell you that I had tried in full and returned this error.

  • 1

    Do not mask the error with this catch, let the exception pop and paste the stack of errors here.

  • tries to make: itens = Double.parseDouble( ((String) jtbRacao.getValueAt(i,3)).replace(",", ".") );

  • Douglas, it didn’t work out! I think it’s not a comma related problem, because I tried to calculate changing the variable to integer and also did not give.

  • When I take the specific cell it seems to me that it returns an Object. It may have some relation?

  • By mistake, it seems to me the fault of the comma itself. It makes System.out.println(jtbRacao.getValueAt(i, 3)); and tell us the way out, so we know what is being returned there.

  • 3.58 I will post the image of the column that I am picking up the values...

  • "3.58" won’t convert to Double, but "3.58" should. From what I understand, you’re saying that even "3.58" isn’t converting? Run this: System.out.println("Valor convertido: "+Double.parseDouble("3.58")); If until this line launch an Exception, then I have no idea how to solve your problem.

  • Exception in thread "AWT-Eventqueue-0" 3.58 5.07 java.lang.Arrayindexoutofboundsexception: 2 >= 2 at java.util.Vector.elementAt(Unknown Source) at javax.swing.table.DefaultTableModel.getValueAt(Unknown Source) at javax.swing.Jtable.getValueAt(Unknown Source) at VIEW.Telaracao$7.actionPerformed(Telaracao.java:313)

  • I changed the column values to "3.58" and "5.07" and calculated...see the result above.

  • 1

    Douglas, I discovered...actually there were two errors: what you indicated about changing the comma by the point and the other was getColumnCount q actually the correct one is getRowCount...!

  • Great, if someone’s answer below solves your problem, mark it as accepted; otherwise, create an answer and mark it as accepted. :)

Show 9 more comments

2 answers

3

Some points I saw here:

  1. On the screen, the column should be showing decimal places with "," rather than ".", which is what is expected by the method Double.parseDouble(). Use the class java.text.NumberFormat to convert and format values from and to localized strings.
  2. In the loop for, you are going from 0 to the number of columns, should actually go up to the number of lines.
  3. To add up values and other operations that need precision, it is not good to use nor float nor double, for being floating points. It is more interesting to use the class java.math.BigDecimal.

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

1

Apparently your problem must be in converting String value to Double, tries to replace a comma to a point.

Ex:

String valor = "9,99"
valor = valor.replace(",", ".");
Double valorDouble = Double.parseDouble(valor);
  • Felipe, I tried your suggestion but unfortunately it didn’t work...

Browser other questions tagged

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