Error in Java - Calculation of the square root

1

I was doing some basic exercises in Java and one of them asked:

  

In this example, we will use the sqrt method of the Math class to extract the square root of the number that is typed into a text box, a 'Text field' component for the user to enter the desired number, and a 'Label' component to display the result, that is, the square root of that number.

Then I did everything right, but it gave a problem, when I type the 1 letter:

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 Apresentacao.TelaRaiz.jtNumeroKeyPressed(TelaRaiz.java:67)
    at Apresentacao.TelaRaiz.access$000(TelaRaiz.java:12)
    at Apresentacao.TelaRaiz$1.keyPressed(TelaRaiz.java:38)
    at java.awt.Component.processKeyEvent(Component.java:6491)
    at javax.swing.JComponent.processKeyEvent(JComponent.java:2832)
    at java.awt.Component.processEvent(Component.java:6310)
    at java.awt.Container.processEvent(Container.java:2236)
    at java.awt.Component.dispatchEventImpl(Component.java:4889)
    at java.awt.Container.dispatchEventImpl(Container.java:2294)
    at java.awt.Component.dispatchEvent(Component.java:4711)
    at java.awt.KeyboardFocusManager.redispatchEvent(KeyboardFocusManager.java:1954)
    at java.awt.DefaultKeyboardFocusManager.dispatchKeyEvent(DefaultKeyboardFocusManager.java:806)
    at java.awt.DefaultKeyboardFocusManager.preDispatchKeyEvent(DefaultKeyboardFocusManager.java:1074)
    at java.awt.DefaultKeyboardFocusManager.typeAheadAssertions(DefaultKeyboardFocusManager.java:945)
    at java.awt.DefaultKeyboardFocusManager.dispatchEvent(DefaultKeyboardFocusManager.java:771)
    at java.awt.Component.dispatchEventImpl(Component.java:4760)
    at java.awt.Container.dispatchEventImpl(Container.java:2294)
    at java.awt.Window.dispatchEventImpl(Window.java:2746)
    at java.awt.Component.dispatchEvent(Component.java:4711)
    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$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:80)
    at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:90)
    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$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:80)
    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)

It performs everything and even with error it calculates the root, but only when I type the second letter, or when I type the first letter and press ENTER. Why are you making this mistake? I wanted it when I typed, it captures and shows the result.

Error Excerpt:

private void jtNumeroKeyPressed(java.awt.event.KeyEvent evt) {                                    
        int i = (int)(Double.parseDouble(jtNumero.getText()));
        jlResultado.setText("A raiz quadrada de: "+ i + " é: " + Math.sqrt(i));
    }
    
asked by anonymous 08.06.2017 / 15:52

3 answers

3

The error occurs because an empty String is being passed to the parse method. Try to validate before capturing the value of the field:

private void jtNumeroKeyPressed(java.awt.event.KeyEvent evt){
    String valor = jtNumero.getText().trim();

    if(valor.isEmpty()){
        //exibe algo se o campo estiver vazio
    } else {
        int i = (int)(Double.parseDouble(valor));
        jlResultado.setText("A raiz quadrada de: "+ i + " é: " + Math.sqrt(i));
    }
}
    
08.06.2017 / 15:58
1

The problem is that you are using the KeyPressed event. This event captures the key pressed, but at this point the component's text attribute is still with the old value. Use the KeyReleased event because it fires after the key is released and the text is already in the final content.

private void jtNumeroKeyReleased(java.awt.event.KeyEvent evt) {                                        
    if ("".equals(jtNumero.getText())){return;}
    int i = (int)(Double.parseDouble(jtNumero.getText()));
    jlResultado.setText("A raiz quadrada de: "+ i + " é: " + Math.sqrt(i));
}                                       
    
08.06.2017 / 16:08
1

Try to do this:

private void jtNumeroKeyPressed(java.awt.event.KeyEvent evt) {
    try {                     
        double i = Double.parseDouble(jtNumero.getText());
        jlResultado.setText("A raiz quadrada de " + i + " é " + Math.sqrt(i) + ".");
    } catch (NumberFormatException e) {
        jlResultado.setText("Por favor, digite um número válido.");
    }
}

Here, catch is catching the exception if the value entered is not numeric. Additionally, the value you enter must be double , not int . In this way, the square root of 1.21 will be 1.1 , not 1 .

    
08.06.2017 / 16:09