Solved

implementing a thread

Posted on 2003-11-02
13
245 Views
Last Modified: 2013-11-23
How can i implement a thread on the following code: (I want to run the "private double computeAnswer"  every 2seconds)

import java.awt.*;
import java.applet.*;
import java.awt.event.*;


public class GreetingApplet extends Applet implements ActionListener
{
// DATA MEMBERS
      private Label prompt;
      private Label equal;
      private TextField inputLine;
      private TextField inputLine2;
      
      double Answer = 0;
//CONSTRUCTOR
      
      public GreetingApplet()            
      {
            // create gui objects
            prompt = new Label("Please enter 2 numbers");
            equal = new Label();
            inputLine = new TextField(5);
            inputLine2 = new TextField(5);
            
            //add gui objects to applet
            add(prompt);
            add(equal);
            add(inputLine);
            add(inputLine2);
            
            //add actionlistener
            inputLine.addActionListener(this);
            inputLine2.addActionListener(this);
      }
      
      public void actionPerformed(ActionEvent event)
      {
            String input1String, input2String, result;
            double input1, input2;
            //int Answer;
            
            /*      greeting.setText("nice to meet you " + inputLine.getText()+ " " + inputLine2.getText()+".");
            add(greeting);
            doLayout();
            */
            
            //Get input values
            input1String = inputLine.getText();
            input2String = inputLine2.getText();
            
            //convert string/input to numerical value
            input1 = convertToDouble(input1String);
            input2 = convertToDouble(input2String);
            
            //Compute Answer
            Answer = computeAnswer(input1, input2);
            
            //Display result
            result = "Your Answer is" + Answer;
            equal.setText(result);
            
            add(equal);
            doLayout();
      }
                                                                        
      private double convertToDouble(String str)
{                                             
      Double doubleObj = new Double(str);
      return doubleObj.doubleValue();
}


      private double computeAnswer(double input1, double input2)
      {
        //run this in a thread so it calculates every 2 seconds
            Answer = (Answer + 0.1*(input1-input2));
            
            return Answer;
      }
}
0
Comment
Question by:lisa_davis
  • 6
  • 5
  • 2
13 Comments
 
LVL 92

Expert Comment

by:objects
ID: 9667732
What values do you want to be passing to computeAnswer every 2 secs?
0
 

Author Comment

by:lisa_davis
ID: 9667797
I dont really understand your question but....

I would like to have the new value of 'Answer' put into the equation of

'Answer = (Answer + 0.1*(input1-input2));'

and also the input values given as input1 and input2


0
 

Author Comment

by:lisa_davis
ID: 9667810
eg. if the applet is ran and enter is pressed after valid numbers are entered into inputLine and inputLine2 then the answer is what i want.
If i keep pressing enter the value is added to the currect value in Answer

But how do i make this occur so that enter does not have to be pressed by the use of threads?

if that makes sense?

sorry im very new to java
0
 
LVL 92

Assisted Solution

by:objects
objects earned 50 total points
ID: 9667832
Something like the following perhaps though I'm a little unclear on what you are trying to achieve:

public void run()
{
   try
   {
      double input1 = convertToDouble(inputLine.getText());
      double input2 = convertToDouble(inputLine2.getText());
      while (true)
      {
         computeAnswer(input1, input2);
         Thread.sleep(2000);
      }
   }
   catch (Exception ex)
   {
      ex.printStackTrace();
   }
}

0
 
LVL 16

Accepted Solution

by:
gnoon earned 75 total points
ID: 9677041
Is this your goal?

import java.awt.*;
import java.applet.*;
import java.awt.event.*;


public class GreetingApplet extends Applet implements ActionListener
{
// DATA MEMBERS
     private Label prompt;
     private Label equal;
     private TextField inputLine;
     private TextField inputLine2;

     double Answer = 0;
//CONSTRUCTOR

     public GreetingApplet()
     {
          // create gui objects
          prompt = new Label("Please enter 2 numbers");
          equal = new Label();
          inputLine = new TextField(5);
          inputLine2 = new TextField(5);

          //add gui objects to applet
          add(prompt);
          add(inputLine);
          add(inputLine2);
          add(equal);

          //add actionlistener
          inputLine.addActionListener(this);
          inputLine2.addActionListener(this);
     }

     public void actionPerformed(ActionEvent event)
     {
        new Thread() {
            public void run() {
                while(true) {
                    String input1String, input2String, result;
                    double input1, input2;
                    double Anstemp = Answer;

                    /*     greeting.setText("nice to meet you " + inputLine.getText()+ " " + inputLine2.getText()+".");
                    add(greeting);
                    doLayout();
                    */

                    //Get input values
                    input1String = inputLine.getText();
                    input2String = inputLine2.getText();

                    //convert string/input to numerical value
                    input1 = convertToDouble(input1String);
                    input2 = convertToDouble(input2String);

                    //Compute Answer
                    Answer = computeAnswer(input1, input2);

                    //Display result
                    result = "("+String.valueOf(Anstemp)+" + 0.1*("+String.valueOf(input1)+" - "+
                      String.valueOf(input2) +")) = "+ String.valueOf(Answer);
                    equal.setText(result);

                    equal.setText(result);
                    doLayout();
                    // sleep 2 sec
                    try{Thread.sleep(2000);}catch(Exception e){e.printStackTrace();}
                }
            }
        }.start();
     }

     private double convertToDouble(String str)
{
     try {
        return new Double(str).doubleValue();
     } catch(NumberFormatException e){ return 0f; }
}


     private double computeAnswer(double input1, double input2)
     {
        //run this in a thread so it calculates every 2 seconds
          Answer = (Answer + 0.1*(input1-input2));
          return Answer;
     }
}

// <applet code="GreetingApplet" width=400 height=400></applet>
0
 

Author Comment

by:lisa_davis
ID: 9678170
Thanks for that gnoon

although the line :
catch(NumberFormatException e){ return 0f; }

returns a float?

how do i set this to an int or double value?
0
IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

 
LVL 92

Expert Comment

by:objects
ID: 9681784
How is that different to what I already posted?
0
 

Author Comment

by:lisa_davis
ID: 9683487
Sorry objects

im new to java, especially threads and got confused when i only seen that code
0
 
LVL 92

Expert Comment

by:objects
ID: 9683489
0
 
LVL 92

Expert Comment

by:objects
ID: 9683498
If you need clarification in the future feel free to ask :)
0
 
LVL 16

Expert Comment

by:gnoon
ID: 9684442
Objects,
   I am sorry that my code is like to your algorithm. I just want to show the complete class and how convertToDouble method handles the number exception when no number entered to lisa_davis.

lisa_davis,
   If you want to return an int or and double from convertToDouble method, you should use 'return <number>;' which <number> type is less than or equal double and the same family (such as byte, char, short, int, long, float), the jvm will automatic cast the value to the method return type. In this case, not different between 'return 0f;' or 'return 0.0;' or 'return 0;'.

Let me know if something wrong.
-gnoon-
0
 
LVL 92

Expert Comment

by:objects
ID: 9684451
Thats fine :)
0
 

Author Comment

by:lisa_davis
ID: 9685230
Thanks guys :)
0

Featured Post

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
scoresSpecial  challenge 13 40
java set up 1 46
unix in java example 9 40
Java Jpanels and Jframe 8 20
Introduction This article is the first of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article explains our test automation goals. Then rationale is given for the tools we use to a…
Basic understanding on "OO- Object Orientation" is needed for designing a logical solution to solve a problem. Basic OOAD is a prerequisite for a coder to ensure that they follow the basic design of OO. This would help developers to understand the b…
Viewers learn about the “while” loop and how to utilize it correctly in Java. Additionally, viewers begin exploring how to include conditional statements within a while loop and avoid an endless loop. Define While Loop: Basic Example: Explanatio…
This tutorial covers a step-by-step guide to install VisualVM launcher in eclipse.

706 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

18 Experts available now in Live!

Get 1:1 Help Now