Search code examples
javaswingjtextarea

Showing error output in Jtextarea using netbeans


I am creating a small application like calculator. I have jTextField,jTextArea and a Jbutton. When I type 121 and then button click I want to get the answer as 4 in Jtextarea. But when I click I am getting wrong answer as 242.

Following is my code:

 private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
        int va=Integer.parseInt( jTextField1.getText());
       int  vb= Integer.parseInt(jTextField1.getText());
      int ca= va+vb;
      jTextArea1.append(Integer.toString(ca));
      jTextArea1.append("\n");
    }

Solution

  • You're getting text from the same field twice, so 121+121 is 242...

    But I want to get the answer as 1+2+1=4

    Then you need to take each character in the String and add them together, for example...

        String text = "121";
        int result = 0;
        for (char c : text.toCharArray()) {
            result += Integer.parseInt(Character.toString(c));
        }
    
        System.out.println(result);
    

    Which prints 4