0% found this document useful (0 votes)
4 views

Lecture 8- 13-Feb-2025

The document provides an overview of the Math class in Java, detailing its static methods and constants for performing mathematical operations. It includes examples of using the Math class in a Quadratic equation program and demonstrates formatting output using NumberFormat and DecimalFormat classes. Additionally, it covers the printf method for formatted string output, illustrating various format specifiers.

Uploaded by

L A A
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Lecture 8- 13-Feb-2025

The document provides an overview of the Math class in Java, detailing its static methods and constants for performing mathematical operations. It includes examples of using the Math class in a Quadratic equation program and demonstrates formatting output using NumberFormat and DecimalFormat classes. Additionally, it covers the printf method for formatted string output, illustrating various format specifiers.

Uploaded by

L A A
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 13

The Math Class

• The Math class is part of the java.lang package


• The Math class contains methods that perform various mathematical functions
• The Math class contains static constants:
• PI, The constant can be used through the class name
Areaofcircle=radius*radius*Math.PI;

• These include:
• int abs ( int num ); absolute value
• double sqrt (double num ); square root
• double sin (double angle); trigonometric functions
• double ceil ( double num); the smallest number greater than num or equal.
• double floor ( double num); the largest number less than num or equal.
• double pow ( double num, double power);
• double random(); 0.0 – 1.0

3-29
The Math Class
• The methods of the Math class are static methods (also called class
methods)
• Static methods can be invoked through the class name – no object of
the Math class is needed
value = Math.cos(90) + Math.sqrt(delta);
• You can pass an integer value to method that accept a double.

• See Quadratic.java (page 129)

• See Math class. (page 128)


3-31
Quadratic.java
import java.util.Scanner;
public class Quadratic -b ± b2 -4ac
{
2a
// Determines the roots of a quadratic equation.
public static void main (String[] args)
{
int a, b, c;
double discriminant, root1, root2;
Scanner scan = new Scanner (System.in);
System.out.print ("Enter the coefficient of x squared: ");
a = scan.nextInt();
System.out.print ("Enter the coefficient of x: ");
b = scan.nextInt();
System.out.print ("Enter the constant: ");
c = scan.nextInt();
// Use the quadratic formula to compute the roots.
discriminant = Math.pow(b, 2) - (4 * a * c);
root1 = ((-1 * b) + Math.sqrt(discriminant)) / (2 * a);
root2 = ((-1 * b) - Math.sqrt(discriminant)) / (2 * a);

System.out.println ("Root #1: " + root1);


System.out.println ("Root #2: " + root2);
} 3-32
}
Quadratic.java
import java.util.Scanner;
public class Quadratic -b ± b2 -4ac
{
2a
// Determines the roots of a quadratic equation.
public static void main (String[] args)
{
int a, b, c;
double discriminant, root1, root2;
Scanner scan = new Scanner (System.in);
System.out.print ("Enter the coefficient of x squared: ");
a = scan.nextInt();
System.out.print ("Enter the coefficient of x: ");
b = scan.nextInt();
System.out.print ("Enter the constant: ");
c = scan.nextInt();
// Use the quadratic formula to compute the roots.
discriminant = Math.pow(b, 2) - (4 * a * c);
root1 = ((-1 * b) + Math.sqrt(discriminant)) / (2 * a);
root2 = ((-1 * b) - Math.sqrt(discriminant)) / (2 * a);

System.out.println ("Root #1: " + root1);


System.out.println ("Root #2: " + root2);
} 3-33
}
Outline
Creating Objects
The String Class
Packages
Formatting Output
Enumerated Types
Wrapper Classes

3-34
Formatting Output
• It is often necessary to format values in certain ways so that they can be
presented properly
• The Java standard class library contains classes that provide formatting
capabilities
• The NumberFormat class allows you to format values as currency or
percentages
• The DecimalFormat class allows you to format values based on a
pattern
• Both are part of the java.text package

3-35
Formatting Output- Number Format
• The NumberFormat class has static methods that return a
formatter object ( no need to use new )
Static NumberFormat getCurrencyInstance()
Static NumberFormat getPercentInstance()
• Each formatter object has a method called format that returns a
string with the specified information in the appropriate format
• String format ( double number )
import java.text.NumberFormat;
NumberFormat fmt = NumberFormat.getCurrencyInstance();
• See Purchase.java (page 131) String formattedAmount = fmt.format(amount);

3-36
Purchase.java Enter the quantity: 5
Enter the unit price: 3.87
import java.util.Scanner; Subtotal: $19.35
import java.text.NumberFormat; Tax: $1.16 at 6%
public class Purchase Total: $20.51
{
public static void main (String[] args)
{
final double TAX_RATE = 0.06; // 6% sales tax
int quantity;
double subtotal, tax, totalCost, unitPrice;
Scanner scan = new Scanner (System.in);
NumberFormat fmt1 = NumberFormat.getCurrencyInstance();
NumberFormat fmt2 = NumberFormat.getPercentInstance();
System.out.print ("Enter the quantity: "); quantity = scan.nextInt();
System.out.print ("Enter the unit price: "); unitPrice = scan.nextDouble();
subtotal = quantity * unitPrice;
tax = subtotal * TAX_RATE;
totalCost = subtotal + tax;
// Print output with appropriate formatting
System.out.println ("Subtotal: " + fmt1.format(subtotal));
System.out.println ("Tax: " + fmt1.format(tax) + " at " + fmt2.format(TAX_RATE));
System.out.println ("Total: " + fmt1.format(totalCost));
} 3-37
}
Formatting Output- Decimal Format
• The DecimalFormat class can be used to format a floating point value in various ways
• The DecimalFormat class unlike NumberFormat (must use new)
• For example, you can specify that the number should be truncated to three decimal places
• The constructor of the DecimalFormat class takes a string that represents a pattern for the
formatted number
See CircleStats.java (page 134)

import java.text.DecimalFormat;
DecimalFormat fmt = new DecimalFormat ("0.###");
fmt.format(circumference); // circumference is double

3-38
CircleStats.java
import java.util.Scanner;
import java.text.DecimalFormat;
public class CircleStats
{
public static void main(String[] args)
{
int radius;
double area, circumference;
Scanner scan = new Scanner(System.in);
System.out.print("Enter the circle's radius: ");
radius = scan.nextInt();
area = Math.PI * Math.pow(radius, 2);
circumference = 2 * Math.PI * radius;
// Round the output to three decimal places
DecimalFormat fmt = new DecimalFormat("0.###");
System.out.println("The circle's area: " + fmt.format(area));
System.out.println("The circle's circumference: "+ fmt.format(circumference));
}
}
Formatting Output
• The printf method allows the use to print a formatted string containing data value.

System.out.printf( “ ID : %5d\t Name: %10s”, id, name)

The format of the output


The values

%d: Integer (decimal).


• %5d: the id value should print in 5 characters %s: String.
%f: Floating-point number.
• %10s: the name string should print in 10 characters %x: Hexadecimal.
• if %s means match the string length. %o: Octal.
%b: Boolean.
%c: Character.
%e: Scientific notation.
3-40
Formatting Output- Example
double price = 19.99;
System.out.printf("%f", price); // Output: 19.990000 (default to 6 decimal places)
System.out.printf("%.2f", price); // Output: 19.99
int num = 255;
System.out.printf("%x", num); // Output: ff
boolean isActive = true;
System.out.printf("%b", isActive); // Output: true
double value = 12345.6789;
System.out.printf("%e", value); // Output: 1.234568e+04

You might also like