No—bugs are not allowed in restaurants, nor in programs.
All of the familiar mathematical functions
that are found on an electronic calculator such as
sine, log, and square root
are available to your program in the Java Math
class.
Typically these functions expect data type double
as
an actual parameter and return a double
value.
Here is a program that reads in a floating point number from the keyboard and prints out its square root:
import java.io.*;
class SquareRoot
{
public static void main (String[] args) throws IOException
{
String charData;
double value;
// read in a double
BufferedReader stdin = new BufferedReader
(new InputStreamReader(System.in));
System.out.print ("Enter a double:");
charData = stdin.readLine();
value = Double.parseDouble( charData ) ;
// calculate its square root
double result = Math.sqrt( value );
// write out the result
System.out.println("square root: " + result );
}
}
The assignment statement (in blue) uses the sqrt()
method
of the class Math
.
This is a static method, which means that you ask for it using the
name of a class and a
dot operator, like this:
Class . method ( parameters )