2d

Advanced Placement

Computer Science Lab

 

 

Introduction to the Math Class & the Number Format Class

 

 

 

 

Introduction

 

Another useful class is the Math class.  Because many of the methods of the Math class are static methods, the Math class does not have to be instantiated like the string class to access the methods, but rather the methods are accessed by using the name of the class, e.g. Math.pow (b, 2);. Some of the methods of the Math class are as follows:

 

 

 

 

 

 

static int abs(int num)

//Returns the absolute value of num.

 

static double cos (double angle)

static double sin (double angle)

static double tan (double angle)

//Returns indicated trigometric value for angle in radians

 

static double acos (double angle)

static double asin (double angle)

static double atan (double angle)

//Returns arc trigometric value

 

static double exp (double num)

//Returns the value e raised to the specified value

 

static double pow (double num, double power)

//Returns the value num raised to the specified value of power

 

static double random ()

//Returns a random value between 0.0 and 1.0

 

static double sqrt (double num)

//Returns the square root of num

 

 

 

 

 

 

The DecimalFormat class allows you to format numerical output.  In order to use the DecimalFormat class you must import it using the statement import java.text.DecimalFormat; .  When you instantiate the class, you provide the object created with a template for the format.  The methods are as follows:

 

 

 

 

 

 

DecimalFormat(String pattern)

//Invokes the constructor of the object and creates an object with the specified pattern, e.g. “0.###” will format number with three decimal places.

 

void applyPattern(String pattern)

//Allows to change the pattern

 

String format(double num)

//Returns a string containing the number formatted according to the pattern

 

 

 

 

 

 

 

Programming Assignment

 

Write the following short programs.  Remember to import the appropriate class at the beginning of the program.

 

Start a new project, UnitConversion, and write an application program in the project that will convert inches to feet, yards, meters, centimeters, millimeters and kilometers. Input should request user to input some number of inches. Format the output to hundredths using the Decimal Format class. 

 

Start a new project, Quadratic, and write an application program in the project that will convert find the roots of a quadratic equation in which the coefficients are entered by the user.  Use the Math class to perform exponentiation and square root functions.  Include in your comments some test cases that known to work.  Format the output to hundredths using the Decimal Format class.