Foros aprenderaprogramar.com

Aprender a programar => C, C++, C#, Java, Visual Basic, HTML, PHP, CSS, Javascript, Ajax, Joomla, MySql y más => Mensaje iniciado por: Raquel en 23 de Agosto 2021, 02:43

Título: Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: empty St
Publicado por: Raquel en 23 de Agosto 2021, 02:43
Hola ¿me podrían ayudar? No sé por qué me sale un error en este código. (Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: empty String)


Código: [Seleccionar]
public class GUIFigura extends javax.swing.JFrame {
//LO QUE QUIERO ESQ MUESTRE EL AREA Y VOLUMEN DE CADA FIGURA QUE ESCOGA Y ME SALE ERROR.
    Figura figuras[];
    int contador = 0;



    private void btnGuardarActionPerformed(java.awt.event.ActionEvent evt) {                                           

        double radio = Double.parseDouble(txtradio.getText());
        System.out.println("El radio es" + radio);
        double lado = Double.parseDouble(txtlado.getText());
        double ladoCubo = Double.parseDouble(txtladoCubo.getText());
        double base = Double.parseDouble(txtbase.getText());
        double altura = Double.parseDouble(txtaltura.getText());
        double radioEsfera = Double.parseDouble(txtRadioEsfera.getText());
        double arista = Double.parseDouble(txtarista.getText());

        if (contador < figuras.length) {
            if (rbtCirculo.isSelected()) {
                figuras[contador] = new Circulo(radio);
            }
            if (rbtCuadrado.isSelected()) {

                figuras[contador] = new Cuadrado(lado);
            }
            if (rbtTriangulo.isSelected()) {

                figuras[contador] = new Triangulo(base, altura);

            }
            if (rbtEsfera.isSelected()) {

                figuras[contador] = new Esfera(radio);
            }
            if (rbtCubo.isSelected()) {

                figuras[contador] = new Cubo(lado);

            }
            if (rbtTetraedro.isSelected()) {

                figuras[contador] = new Tetraedro(arista);
            }
            contador++;


    }                                         
    }

    private void btnInformacionActionPerformed(java.awt.event.ActionEvent evt) {                                               
        // TODO add your handling code here:

        for (int i = 0; i < figuras.length; i++) {
            txaInformacion.setText(txaInformacion.getText()
                    + "En el indice " + i + " Se guarda " + figuras[i].getClass().getSimpleName()
                    + " y su area es " + figuras[i].calcularArea());
            if (figuras[i] instanceof FiguraTridimensional) {
                txaInformacion.setText(txaInformacion.getText() + " Y su volumen es " + ((FiguraTridimensional) figuras[i]).calcularVolumen());
            }
//         
        }
    }                                             

    private void rbtCirculoActionPerformed(java.awt.event.ActionEvent evt) {                                           
        // TODO add your handling code here:
        txtradio.setEnabled(true);
        txtRadioEsfera.setEnabled(false);
        txtaltura.setEnabled(false);
        txtarista.setEnabled(false);
        txtlado.setEnabled(false);
        txtbase.setEnabled(false);
        txtaltura.setEnabled(false);
        txtladoCubo.setEnabled(false);
    }                                         

    private void txtradioActionPerformed(java.awt.event.ActionEvent evt) {                                         
        // TODO add your handling code here:


    }                                       

    private void txtradioKeyReleased(java.awt.event.KeyEvent evt) {                                     
        // TODO add your handling code here:

    }                                   

    private void rbtCuadradoActionPerformed(java.awt.event.ActionEvent evt) {                                           
        // TODO add your handling code here:
        txtradio.setEnabled(false);
        txtRadioEsfera.setEnabled(false);
        txtaltura.setEnabled(false);
        txtarista.setEnabled(false);
        txtlado.setEnabled(true);
        txtbase.setEnabled(false);
        txtaltura.setEnabled(false);
        txtladoCubo.setEnabled(false);
    }                                           

    private void rbtTrianguloActionPerformed(java.awt.event.ActionEvent evt) {                                             
        // TODO add your handling code here:
        txtradio.setEnabled(false);
        txtRadioEsfera.setEnabled(false);
        txtaltura.setEnabled(false);
        txtarista.setEnabled(false);
        txtlado.setEnabled(false);
        txtbase.setEnabled(true);
        txtaltura.setEnabled(true);
        txtladoCubo.setEnabled(false);
    }                                           

    private void rbtEsferaActionPerformed(java.awt.event.ActionEvent evt) {                                         
        // TODO add your handling code here:
        txtradio.setEnabled(false);
        txtRadioEsfera.setEnabled(true);
        txtaltura.setEnabled(false);
        txtarista.setEnabled(false);
        txtlado.setEnabled(false);
        txtbase.setEnabled(false);
        txtaltura.setEnabled(false);
        txtladoCubo.setEnabled(false);
    }                                         

    private void rbtCuboActionPerformed(java.awt.event.ActionEvent evt) {                                       
        // TODO add your handling code here:
        txtradio.setEnabled(false);
        txtRadioEsfera.setEnabled(false);
        txtaltura.setEnabled(false);
        txtarista.setEnabled(false);
        txtlado.setEnabled(false);
        txtbase.setEnabled(false);
        txtaltura.setEnabled(false);
        txtladoCubo.setEnabled(true);
    }                                       

    private void rbtTetraedroActionPerformed(java.awt.event.ActionEvent evt) {                                             
        // TODO add your handling code here:
        txtradio.setEnabled(false);
        txtRadioEsfera.setEnabled(false);
        txtaltura.setEnabled(false);
        txtarista.setEnabled(true);
        txtlado.setEnabled(false);
        txtbase.setEnabled(false);
        txtaltura.setEnabled(false);
        txtladoCubo.setEnabled(false);
    }                                           

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;

                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(GUIFigura.class
                    .getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(GUIFigura.class
                    .getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(GUIFigura.class
                    .getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(GUIFigura.class
                    .getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new GUIFigura().setVisible(true);
            }
        });

    }

    public void limpiarGUI() {
        txtaltura.setText(null);
        txtarista.setText(null);
        txtRadioEsfera.setText(null);
        txtladoCubo.setText(null);
        txtradio.setText(null);
        txtlado.setText(null);
        txtbase.setText(null);

    }


ERRORES QUE ME ME SALEN

Citar
Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: empty String at

java.base/jdk.internal.math.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:1842)
   at java.base/jdk.internal.math.FloatingDecimal.parseDouble(FloatingDecimal.java:110)
   at java.base/java.lang.Double.parseDouble(Double.java:549)
   at deberfigura.GUIFigura.btnGuardarActionPerformed(GUIFigura.java:312)
   at deberfigura.GUIFigura$1.actionPerformed(GUIFigura.java:84)
   at java.desktop/javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1967)
   at java.desktop/javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2308)
   at java.desktop/javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:405)

                 
Título: Re: Hola me podrían ayudar porq me sale un error en este código
Publicado por: Kabuto en 23 de Agosto 2021, 12:15
Hola.
Por lo que indica el error, parece que alguno/s de estos Double.parseDouble() recibe un String vacío, y que por tanto no se puede parsear..

Código: [Seleccionar]
        double radio = Double.parseDouble(txtradio.getText());
        System.out.println("El radio es" + radio);
        double lado = Double.parseDouble(txtlado.getText());
        double ladoCubo = Double.parseDouble(txtladoCubo.getText());
        double base = Double.parseDouble(txtbase.getText());
        double altura = Double.parseDouble(txtaltura.getText());
        double radioEsfera = Double.parseDouble(txtRadioEsfera.getText());
        double arista = Double.parseDouble(txtarista.getText());

No se como es el resto de tu programa ni tu GUI, así que solo puedo hacer suposiciones.
Y una suposición es que quizá el problema sea que tú coges los datos de TODAS las figuras, pero quizá el usuario en la GUI solo ha seleccionado una figura y es a esta a la que ha puesto unos valores.
Si el resto de figuras no reciben valores en sus campos de texto (tienen String vacío) y tú intentas recoger y parsear esos campos vacíos, pues entonces se produce esa excepción que te sale en pantalla.

Quizás no deberías coger los datos de TODAS las figuras, solo los de la figura seleccionada.
Puesto que en ese mismo código luego preguntas cuál es la figura seleccionada, pues s entonces cuando deberías recoger el dato necesario.

Por ejemplo:
Citar
if (rbtCirculo.isSelected()) {
            figuras[contador] = new Circulo(Double.parseDouble(txtradio.getText()));
}
if (rbtCuadrado.isSelected()) {
            figuras[contador] = new Cuadrado(Double.parseDouble(txtlado.getText()));
}
etc....


Incluso, para mayor seguridad, antes de coger el dato puedes comprobar que realmente tiene un valor introducido y solo entonces intentas el parseo y creación de la figura

Citar
if (rbtCirculo.isSelected()) {
            if (txtradio.getText().isBlank())
                        JOptionPane.showMessageDialog(null, "Se necesita valor del radio para crear Circulo");
            else
                        figuras[contador] = new Circulo(Double.parseDouble(txtradio.getText()));
}
if (rbtCuadrado.isSelected()) {
            if (txtlado.getText().isBlank())
                        JOptionPane.showMessageDialog(null, "Se necesita valor del lado para crear Cuadrado");
            else
                        figuras[contador] = new Cuadrado(Double.parseDouble(txtlado.getText()));
}
etc....
Título: Re: Hola me podrían ayudar porq me sale un error en este código
Publicado por: Raquel en 24 de Agosto 2021, 18:17
Muchas gracias. Me ayudó bastante.