Java error - Square root calculation

Asked

Viewed 1,055 times

1

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

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

Then I did everything right, only 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 runs 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 hit ENTER. Why are you making this mistake? I wanted when I typed it to capture and show the result.

Excerpt from Error:

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

    Put the snippet of your code where the error occurs so we can better understand.

3 answers

3

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

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));
    }
}
  • There is how you help me, I want that when I type already appear the result tbm, without having to press another key

  • @user41657988463 I do not understand, if the value is passed blank, there is no reason to parse, will give error, as you have already noticed in the question.

  • It’s a mistake, but I type a number

  • 1

    @user41657988463 I still don’t understand.

1

The problem is that you are using the event KeyPressed. This event captures the pressed key, but at this point the text attribute of the component still has the old value. Use the event KeyReleased, because it is triggered after the key is released and the text is already with the definitive 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));
}                                       
  • If it’s a two-digit number, I think the same thing will happen.

  • Negative! Because see that I’m taking the attribute text, which by now will be updated.

  • I would only give this problem that you mentioned if I captured the key by the parameter evt.

1

Try to do so:

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, the catch is capturing the exception if the entered value is not numerical. Also, the entered value must be a double, and not a int. Thus, the square root of 1.21 will be 1.1, and not 1.

Browser other questions tagged

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