Want to win a PS4? Go Premium and enter to win our High-Tech Treats giveaway. Enter to Win

x
?
Solved

implementing a thread

Posted on 2003-11-02
13
Medium Priority
?
253 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
What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

 
LVL 92

Assisted Solution

by:objects
objects earned 200 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 300 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

How to Use the Help Bell

Need to boost the visibility of your question for solutions? Use the Experts Exchange Help Bell to confirm priority levels and contact subject-matter experts for question attention.  Check out this how-to article for more information.

Question has a verified solution.

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

Java contains several comparison operators (e.g., <, <=, >, >=, ==, !=) that allow you to compare primitive values. However, these operators cannot be used to compare the contents of objects. Interface Comparable is used to allow objects of a cl…
Java had always been an easily readable and understandable language.  Some relatively recent changes in the language seem to be changing this pretty fast, and anyone that had not seen any Java code for the last 5 years will possibly have issues unde…
Viewers learn about the scanner class in this video and are introduced to receiving user input for their programs. Additionally, objects, conditional statements, and loops are used to help reinforce the concepts. Introduce Scanner class: Importing…
This tutorial covers a practical example of lazy loading technique and early loading technique in a Singleton Design Pattern.
Suggested Courses

618 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