Presentation is loading. Please wait.

Presentation is loading. Please wait.

Chapter 3 Using Classes and Objects. © 2004 Pearson Addison-Wesley. All rights reserved3-2 Outline Last Time: Creating Objects The GregorianCalendar Class.

Similar presentations


Presentation on theme: "Chapter 3 Using Classes and Objects. © 2004 Pearson Addison-Wesley. All rights reserved3-2 Outline Last Time: Creating Objects The GregorianCalendar Class."— Presentation transcript:

1 Chapter 3 Using Classes and Objects

2 © 2004 Pearson Addison-Wesley. All rights reserved3-2 Outline Last Time: Creating Objects The GregorianCalendar Class The String Class Wrapper Classes Packages Math Class Formatting Output Enumerated Types

3 © 2004 Pearson Addison-Wesley. All rights reserved3-3 Class Libraries A class library is a collection of classes that we can use when developing programs The Java standard class library is part of any Java development environment Its classes are not part of the Java language per se, but we rely on them heavily Various classes we've already used ( System, Scanner, String ) are part of the Java standard class library Other class libraries can be obtained through third party vendors, or you can create them yourself

4 © 2004 Pearson Addison-Wesley. All rights reserved3-4 Packages The classes of the Java standard class library are organized into packages Some of the packages in the standard class library are: Package java.lang java.applet java.awt javax.swing java.net java.util javax.xml.parsers Purpose General support Creating applets for the web Graphics and graphical user interfaces Additional graphics capabilities Network communication Utilities XML document processing

5 © 2004 Pearson Addison-Wesley. All rights reserved3-5 The import Declaration When you want to use a class from a package, you could use its fully qualified name java.util.Scanner Or you can import the class, and then use just the class name import java.util.Scanner; To import all classes in a particular package, you can use the * wildcard character import java.util.*;

6 © 2004 Pearson Addison-Wesley. All rights reserved3-6 The import Declaration All classes of the java.lang package are imported automatically into all programs It's as if all programs contain the following line: import java.lang.*; That's why we didn't have to import the System or String classes explicitly in earlier programs The Scanner class, on the other hand, is part of the java.util package, and therefore must be imported

7 © 2004 Pearson Addison-Wesley. All rights reserved3-7 Outline Packages Math Class Formatting Output Enumerated Types

8 © 2004 Pearson Addison-Wesley. All rights reserved3-8 The Math Class The Math class is part of the java.lang package The Math class contains methods that perform various mathematical functions These include:  absolute value  square root  exponentiation  trigonometric functions  generate random numbers

9 © 2004 Pearson Addison-Wesley. All rights reserved3-9 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); See Quadratic.java (page 129)Quadratic.java discriminant = Math.pow(b, 2) - (4 * a * c); root1 = ((-1 * b) + Math.sqrt(discriminant)) / (2 * a); root2 = ((-1 * b) - Math.sqrt(discriminant)) / (2 * a); We discuss static methods further in Chapter 6

10 © 2004 Pearson Addison-Wesley. All rights reserved3-10 Math Methods MethodPurposeArgumentResult Type abs(x)Returns the absolute value of x any numeric typesame as argument ceil(x)Returns smallest whole number >= x double exp(x)Returns e x where e = 2.71828… double floor(x)Returns the largest whole number <= x double log(x)Returns the natural logarithm of x (base e) for x > 0.0 double

11 © 2004 Pearson Addison-Wesley. All rights reserved3-11 Math Methods MethodPurposeArgumentResult Type max(x,y)Returns the larger of x and y any numeric typesame as argument min(x,y)Returns the smaller of x and y any numeric typesame as argument pow(x,y)Returns x y. An error will occur if x = 0 and y <=0, or x < 0 and y is not a whole number any numeric typedouble random()Returns a pseudorandom number between 0.0 and 1.0 double

12 © 2004 Pearson Addison-Wesley. All rights reserved3-12 Math Methods MethodPurposeArgumentResult Type rint(x)Returns the closest whole number to x double round(x)Returns the integer value closet to x double or floatlong or int sqrt(x)Returns the positive square root of x for x > 0.0 double

13 © 2004 Pearson Addison-Wesley. All rights reserved3-13 Equations Volume of a sphere  Kepler’s Law  where a = radius of orbit, p = period of orbit, G = gravity Brightness of stars

14 © 2004 Pearson Addison-Wesley. All rights reserved3-14 Equations radius of a circle of latitude distance between two points Simulating the rolling of a die – random number between 1 and 6 r Θ rLat

15 © 2004 Pearson Addison-Wesley. All rights reserved3-15 Outline Packages Math Class Formatting Output Enumerated Types

16 © 2004 Pearson Addison-Wesley. All rights reserved3-16 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

17 © 2004 Pearson Addison-Wesley. All rights reserved3-17 Formatting Output The NumberFormat class has static methods that return a formatter object getCurrencyInstance() getPercentInstance() Each formatter object has a method called format that returns a string with the specified information in the appropriate format

18 © 2004 Pearson Addison-Wesley. All rights reserved3-18 See Purchase.java (page 131)Purchase.java NumberFormat fmt1 = NumberFormat.getCurrencyInstance(); NumberFormat fmt2 = NumberFormat.getPercentInstance(); // 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)); Enter the quantity: 3 Enter the unit price: 1.50 Subtotal: $4.50 Tax: $0.27 at 6% Total: $4.77 Output

19 © 2004 Pearson Addison-Wesley. All rights reserved3-19 Formatting Output The DecimalFormat class can be used to format a floating point value in various ways 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

20 © 2004 Pearson Addison-Wesley. All rights reserved3-20 See CircleStats.java (page 134)CircleStats.java // 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)); Enter the circle's radius: 7 The circle's area: 153.938 The circle's circumference: 43.982 Output

21 © 2004 Pearson Addison-Wesley. All rights reserved3-21 Outline Packages Math Class Formatting Output Enumerated Types

22 © 2004 Pearson Addison-Wesley. All rights reserved3-22 Enumerated Types Java allows you to define an enumerated type, which can then be used to declare variables An enumerated type establishes all possible values for a variable of that type The values are identifiers of your own choosing The following declaration creates an enumerated type called Season enum Season {winter, spring, summer, fall}; Any number of values can be listed

23 © 2004 Pearson Addison-Wesley. All rights reserved3-23 Enumerated Types Once a type is defined, a variable of that type can be declared Season time; and it can be assigned a value time = Season.fall; The values are specified through the name of the type Enumerated types are type-safe – you cannot assign any value other than those listed

24 © 2004 Pearson Addison-Wesley. All rights reserved3-24 Ordinal Values Internally, each value of an enumerated type is stored as an integer, called its ordinal value The first value in an enumerated type has an ordinal value of zero, the second one, and so on However, you cannot assign a numeric value to an enumerated type, even if it corresponds to a valid ordinal value

25 © 2004 Pearson Addison-Wesley. All rights reserved3-25 Enumerated Types The declaration of an enumerated type is a special type of class, and each variable of that type is an object The ordinal method returns the ordinal value of the object The name method returns the name of the identifier corresponding to the object's value

26 © 2004 Pearson Addison-Wesley. All rights reserved3-26 See IceCream.java (page 137)IceCream.java //************************************************************* // IceCream.java Author: Lewis/Loftus // // Demonstrates the use of enumerated types. //************************************************************* public class IceCream { enum Flavor {vanilla, chocolate, strawberry, fudgeRipple, coffee, rockyRoad, mintChocolateChip, cookieDough} //---------------------------------------------------------- // Creates and uses variables of the Flavor type. //---------------------------------------------------------- public static void main (String[] args) { Flavor cone1, cone2, cone3; cone1 = Flavor.rockyRoad; cone2 = Flavor.chocolate;

27 © 2004 Pearson Addison-Wesley. All rights reserved3-27 See IceCream.java (page 137)IceCream.java System.out.println ("cone1 value: " + cone1); System.out.println ("cone1 ordinal: " + cone1.ordinal()); System.out.println ("cone1 name: " + cone1.name()); System.out.println (); System.out.println ("cone2 value: " + cone2); System.out.println ("cone2 ordinal: " + cone2.ordinal()); System.out.println ("cone2 name: " + cone2.name()); cone3 = cone1; System.out.println (); System.out.println ("cone3 value: " + cone3); System.out.println ("cone3 ordinal: " + cone3.ordinal()); System.out.println ("cone3 name: " + cone3.name()); }

28 © 2004 Pearson Addison-Wesley. All rights reserved3-28 See IceCream.java (page 137)IceCream.java cone1 value: rockyRoad cone1 ordinal: 5 cone1 name: rockyRoad cone2 value: chocolate cone2 ordinal: 1 cone2 name: chocolate cone3 value: rockyRoad cone3 ordinal: 5 cone3 name: rockyRoad Output

29 © 2004 Pearson Addison-Wesley. All rights reserved3-29 In class exercise Write an application that creates and prints a random phone number of the form XXX-XXX-XXXX. Include the dashes in the output. Do not let the first three digits contain an 8 or 9, make sure that the second set of three digits is not greater than 742, and that neither the first set or second set of digits begin with a 0 or 1. Hint: Think through the easiest way to construct the phone number. Each digit does not have to be determined separately.


Download ppt "Chapter 3 Using Classes and Objects. © 2004 Pearson Addison-Wesley. All rights reserved3-2 Outline Last Time: Creating Objects The GregorianCalendar Class."

Similar presentations


Ads by Google