?
Solved

implementing a thread

Posted on 2003-11-02
13
Medium Priority
?
254 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
VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

 
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

Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say 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

Introduction This article is the last of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers our test design approach and then goes through a simple test case example, how …
In this post we will learn different types of Android Layout and some basics of an Android App.
This tutorial will introduce the viewer to VisualVM for the Java platform application. This video explains an example program and covers the Overview, Monitor, and Heap Dump tabs.
This tutorial explains how to use the VisualVM tool for the Java platform application. This video goes into detail on the Threads, Sampler, and Profiler tabs.
Suggested Courses
Course of the Month14 days, 8 hours left to enroll

840 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