A method is a subroutine that does something. For example, we may want to define and evaluate a function . We will utilize a method to evaluate this function and return the answer to a user-specified location.
Methods must be declared in the main body of your program.
This means they will never be declared in your computeButtonMouseClicked()method, nor in any other method.
In general, methods have the form
<return type> methodName(<type> argument 1, <type> argument 2, …){
//code goes here
return answer of type <return type>;
}
<return type> can be any type of variable or object, such as double,
return answer of type <return type>;
cannot be used.
Here’s an example of a method that calculates . In order to do this, we will need to input x as a double and return the answer as a double. So the method might look like:
double f(double x){
double answer=Math.sin(x)*Math.sin(x); //note the use of the
// Math class here.
// It has lots of functions!
return answer;
}
If we wanted to calculate in the context of our computeButton method and put the result in the variable funcAnswer we would do this by
double funcAnswer=f(Math.PI/4.0);
Some other Math functions and constants can be found here.
See Sample Code 3 to check work
See Sample Code 4 to check work