Solved

implementing a thread

Posted on 2003-11-02
13
247 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
Netscaler Common Configuration How To guides

If you use NetScaler you will want to see these guides. The NetScaler How To Guides show administrators how to get NetScaler up and configured by providing instructions for common scenarios and some not so common ones.

 
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

PRTG Network Monitor: Intuitive Network Monitoring

Network Monitoring is essential to ensure that computer systems and network devices are running. Use PRTG to monitor LANs, servers, websites, applications and devices, bandwidth, virtual environments, remote systems, IoT, and many more. PRTG is easy to set up & use.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
Custom Java Application connects to database: Which one of the 20? 4 29
eclipse buid path vs tomcat lib path 10 24
null output 3 25
Running JavaFX on JDeveloper 12C 1 33
For customizing the look of your lightweight component and making it look lucid like it was made of glass. Or: how to make your component more Apple-ish ;) This tip assumes your component to be of rectangular shape and completely opaque. (COD…
Go is an acronym of golang, is a programming language developed Google in 2007. Go is a new language that is mostly in the C family, with significant input from Pascal/Modula/Oberon family. Hence Go arisen as low-level language with fast compilation…
Viewers learn about the third conditional statement “else if” and use it in an example program. Then additional information about conditional statements is provided, covering the topic thoroughly. Viewers learn about the third conditional statement …
The viewer will learn how to implement Singleton Design Pattern in Java.

832 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