Solved

implementing a thread

Posted on 2003-11-02
13
250 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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
MS Dynamics Made Instantly Simpler

Make Your Microsoft Dynamics Investment Count  & Drastically Decrease Training Time by Providing Intuitive Step-By-Step WalkThru Tutorials.

 
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
 
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

Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
collection output issue 9 89
Java Eclipse Loop 3 43
ArrayList Adding/settign data 3 33
How do i find out all classes which contain nested class 2 10
Java functions are among the best things for programmers to work with as Java sites can be very easy to read and prepare. Java especially simplifies many processes in the coding industry as it helps integrate many forms of technology and different d…
In this post we will learn how to make Android Gesture Tutorial and give different functionality whenever a user Touch or Scroll android screen.
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…
Viewers will learn about basic arrays, how to declare them, and how to use them. Introduction and definition: Declare an array and cover the syntax of declaring them: Initialize every index in the created array: Example/Features of a basic arr…
Suggested Courses

740 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