Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 2 of 2
  1. #1
    New to the CF scene
    Join Date
    Jul 2005
    Posts
    1
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Simple applet - addition of two integers

    Hi folks, as a relative "newbie" to this, I seem to have become slighty stuck on an applet! I need to write a simple applet which provides two TextField objects in which the user can enter positive numbers, one in each; the numbers should be summed and the result displayed in a Label object. The result should not be displayed until both numbers have been entered. The second number should be no longer than 3 digits.
    Here is what I have so far:

    /*an applet which demonstrates the use of text fields*/
    import java.awt.*;

    public class SimpleTextField extends java.applet.Applet
    {
    int num1, num2, num3;
    Label l;
    TextField tf1, tf2;

    public void init()
    {
    add(new Label("Enter first number"));
    tf1 = new TextField(3);
    add(tf1);
    l = new Label("Enter second number");
    add(l);
    tf2 = new TextField(3);
    add(tf2);
    }

    public boolean action(Event evt, Object arg)
    {
    if (evt.target instanceof TextField)
    {
    if(evt.target == tf1)
    {
    num1 = tf1.getText();
    }
    else
    {
    if (tf2.getText().length() > 3)
    {
    l.setText("Number too long");
    }
    else
    {
    num2 = tf2.getText();
    l.setText("valid number");
    }
    }
    repaint();
    }
    return true;
    }

    public void paint(Graphics g)
    {
    g.drawString("The result of your two numbers is: " + num3, 10, 115);
    }
    }


    I'm unsure where I need to put the code that adds the two numbers together.
    Any help would be greatly appreciated.
    Thanks!

  • #2
    Senior Coder
    Join Date
    Mar 2005
    Location
    Portsmouth UK
    Posts
    4,518
    Thanks
    3
    Thanked 506 Times in 493 Posts
    You seem to be talking java

    the text box values are strings so you will need to ensure the input is numbers only with no full stops then the string can be converted to an integer

    Integer.valueOf(MyString);

    the integers can then be added

    much easier with javascript


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •