Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
Chapter 2 Data and Expressions Part Two Outline Character Strings Variables and Assignment Primitive Data Types Expressions Intro to Objects Interactive Programs Data Conversion Graphics Applets Drawing Shapes © 2004 Pearson Addison-Wesley. All rights reserved 2-2 Expressions • An expression is a combination of one or more operators and operands • Arithmetic expressions compute numeric results and make use of the arithmetic operators: Addition Subtraction Multiplication Division Remainder + * / % • If either or both operands used by an arithmetic operator are floating point, then the result is a floating point © 2004 Pearson Addison-Wesley. All rights reserved 2-3 Division and Remainder • If both operands to the division operator (/) are integers, the result is an integer (the fractional part is discarded) 14 / 3 equals 4 8 / 12 equals 0 • The remainder operator (%) returns the remainder after dividing the second operand into the first 14 % 3 equals 2 8 % 12 equals 8 © 2004 Pearson Addison-Wesley. All rights reserved 2-4 Arithmetic Expressions - continued • If operands are mixed, results are ‘promoted.’ 4.5 + 2 = 6.5 (double) Sometimes called “widened.” © 2004 Pearson Addison-Wesley. All rights reserved 2-5 Operator Precedence • Operators can be combined into complex expressions result = total + count / max - offset; • Operators have a well-defined precedence which determines the order in which they are evaluated • Multiplication, division, and remainder are evaluated prior to addition, subtraction, and string concatenation • Arithmetic operators with the same precedence are evaluated from left to right, but parentheses can be used to force the evaluation order © 2004 Pearson Addison-Wesley. All rights reserved 2-6 Operator Precedence • What is the order of evaluation in the following expressions? a + b + c + d + e 1 2 3 4 a + b * c - d / e 3 1 4 2 a / (b + c) - d % e 2 1 4 3 a / (b * (c + (d - e))) 4 3 2 1 © 2004 Pearson Addison-Wesley. All rights reserved 2-7 Expression Trees • The evaluation of a particular expression can be shown using an expression tree • The operators lower in the tree have higher precedence for that expression + a + (b – c) / d / a b © 2004 Pearson Addison-Wesley. All rights reserved d c 2-8 Assignment Revisited • The assignment operator has a lower precedence than the arithmetic operators First the expression on the right hand side of the = operator is evaluated answer = sum / 4 + MAX * lowest; 4 1 3 2 Then the result is stored in the variable on the left hand side Then the result is stored in the variable on the left hand side NOTE: the ‘assignment operator (again) IS an operator – (merely has lower precedence than arithmetic operators….) © 2004 Pearson Addison-Wesley. All rights reserved 2-9 Assignment Revisited • The right and left hand sides of an assignment statement can contain the same variable First, one is added to the original value of count count = count + 1; Then the result is stored back into count (overwriting the original value) KNOW THE OPERATOR PRECEDENCE TABLE ON PAGE 81. It will grow significantly! © 2004 Pearson Addison-Wesley. All rights reserved 2-10 Increment and Decrement • The increment and decrement operators use only one operand • The increment operator (++) adds one to its operand • The decrement operator (--) subtracts one from its operand • The statement count++; is functionally equivalent to count = count + 1; © 2004 Pearson Addison-Wesley. All rights reserved 2-11 Increment and Decrement • The increment and decrement operators can be applied in postfix form: count++ • or prefix form: ++count • When used as part of a larger expression, the two forms can have different effects • Because of their subtleties, the increment and decrement operators should be used with care © 2004 Pearson Addison-Wesley. All rights reserved 2-12 Assignment Operators • Often we perform an operation on a variable, and then store the result back into that variable • Java provides assignment operators to simplify that process • For example, the statement num += count; is equivalent to num = num + count; © 2004 Pearson Addison-Wesley. All rights reserved 2-13 Assignment Operators • There are many assignment operators in Java, including the following: Operator += -= *= /= %= Example x x x x x © 2004 Pearson Addison-Wesley. All rights reserved += -= *= /= %= y y y y y Equivalent To x x x x x = = = = = x x x x x + * / % y y y y y 2-14 Assignment Operators • The right hand side of an assignment operator can be a complex expression • The entire right-hand expression is evaluated first, then the result is combined with the original variable • Therefore result /= (total-MIN) % num; is equivalent to result = result / ((total-MIN) % num); © 2004 Pearson Addison-Wesley. All rights reserved 2-15 Assignment Operators • The behavior of some assignment operators depends on the types of the operands • If the operands to the += operator are strings, the assignment operator performs string concatenation • The behavior of an assignment operator (+=) is always consistent with the behavior of the corresponding operator (+) © 2004 Pearson Addison-Wesley. All rights reserved 2-16 Outline Character Strings Variables and Assignment Primitive Data Types Expressions Intro to Objects Interactive Programs Data Conversion Graphics Applets Drawing Shapes © 2004 Pearson Addison-Wesley. All rights reserved 2-17 Introduction to Objects • An object represents something with which we can interact in a program • An object provides a collection of services that we can tell it to perform for us • The services are defined by methods in a class that defines the object • A class represents a concept. It is abstract. • A class can be used to create multiple objects; that is, multiple instances of the class. © 2004 Pearson Addison-Wesley. All rights reserved 2-18 Introduction to Objects • Object are defined by a class – an abstraction; a generalization. Objects are ‘instances’ of a class. • Operations (methods) are defined by methods in the class. • Methods – a collection of programming statements with a given name that perform some kind of operation © 2004 Pearson Addison-Wesley. All rights reserved 2-19 Objects and Classes A class (the concept) Class = BankAccount Bank Account . Has attributes (data) . Has methods (operations) Classes ‘encapsulate’ attributes and methods. Multiple objects from the same class An object (a realization) (an ‘instantiation’) John’s Bank Account Balance: $5,257 Bill’s Bank Account Balance: $1,245,069 Mary’s Bank Account Balance: $16,833 © 2004 Pearson Addison-Wesley. All rights reserved 2-20 Inheritance • One class can be used to derive another via inheritance • Classes can be organized into inheritance hierarchies Account Think: Human Men Women Charge Account Bank Account Mothers non-Mothers Savings Account © 2004 Pearson Addison-Wesley. All rights reserved Checkin g Account 2-21 Using Objects • The System.out object represents a destination to which we can send output • In the Lincoln program, we invoked the println method of the System.out object: System.out.println ("Whatever you are, be a good one."); object method information provided to the method (parameters) Notice the ‘notation’ for referencing the method: object.method We are SENDING A MESSAGE to the object, System.out. We are requesting that the object perform a ‘service’ for us by invoking. the services of its method, println. © 2004 Pearson Addison-Wesley. All rights reserved 2-22 The print Method • The System.out object provides another service as well • The print method is similar to the println method, except that it does not advance to the next line • Therefore anything printed after a print statement will appear on the same line • Sending a message (fig. 2.2) method within System.out class method: Countdown main System.out println //println //lprint // others… message send to System.out object © 2004 Pearson Addison-Wesley. All rights reserved 2-23 Abstraction (continued) • Of course, we have ‘levels’ of abstraction – germane to the problem at hand. Car • Ford – Mustang » Red Mustang that belongs to ….. Are all levels of abstraction! Each is more and more specific, but all have the ‘is-a’ characteristics. More later….. • Classes and their objects help us write complex software © 2004 Pearson Addison-Wesley. All rights reserved 2-24 Outline Character Strings Variables and Assignment Primitive Data Types Expressions Introduction to Objects Interactive Programs Data Conversion Graphics Applets Drawing Shapes © 2004 Pearson Addison-Wesley. All rights reserved 2-25 Interactive Input (the ‘Return…’) BufferedReader Class; and its methods p. 753-754 • The input stream is made up of multiple objects: Consider: BufferedReader in = new BufferedReader (new InputStreamReader (System.in)); • The System.in (object passed as a parameter) object is used by the InputStreamReader object to create an InputStreamReader object • The InputStreamReader object is then used as a parameter by BufferedReader to create a new BufferedReader object – which is named ‘in.’ • This creates an input stream that treats input as characters and buffers them so that input can be read one line at a time • The readLine method of the BufferedReader class (invoked via in.readLine() reads an entire line of input as a String © 2004 Pearson Addison-Wesley. All rights reserved 2-26 Prelude to Wrapper Classes • Reading text is fine. But we very often need to convert ‘text’ to numbers or other ‘primitives’ for specific processing. • Remember, when we ‘input’ a 14 via keyboard, this is not a 14 (numeric value). It is the ‘character 1 followed by the ‘character 4’ and is really no different than the letter ‘a.’ We canNOT computer with characters. • We CAN print, move, manipulate, etc. with characters. But for those characters that are numbers, we cannot COMPUTE with them. • They are in an internal format (character) that is incompatible with computations. • Enter “Wrapper Classes.” © 2004 Pearson Addison-Wesley. All rights reserved 2-27 Wrapper Classes • • We have classes called Wrapper Classes. Within these classes, we have methods called “Wrapper class methods” (many of these are static methods or class methods….) that can be used to convert text (character) input into desired numeric input • All ‘primitive data types’ (What is a primitive data class?) have Wrapper classes!!!! • Let’s look at some code… • Previews of coming distractions: Problems that arise in reading or converting a value manifest themselves as “Exceptions.” The throws clause of a method header indicates what exceptions it may throw. (Much more later on these…) I/O and exceptions are explored further in a later chapter. © 2004 Pearson Addison-Wesley. All rights reserved 2-28 //******************************************************************** // deleted for space reasons on this slide… //******************************************************************** import java.io.*; import java.text.NumberFormat; public class Wages2 { // Reads pertinent information and calculates wages. public static void main (String[] args) throws IOException { BufferedReader in = new BufferedReader (new InputStreamReader (System.in)); // creates a standard input stream object (a BufferedReader object) in a useful form…. // name if input stream object is ‘in.’ ‘in’ is an object of type (class) BufferedReader. // Creates an input stream that accepts input as characters and buffers the input so that it // can be read one line at a time. ‘in’ now has all the methods defined in BufferedReader. String name; // what does this do? int hours; // what does this do? double rate, pay; System.out.print ("Enter your name: "); name = in.readLine (); // The readLine method of ‘in’, an object of class BufferedReader, reads an entire line of // input as a String (line terminated by ‘Enter’ ). To treat any input as an integer, we must // convert that part of the input String into a numeric form, that is, to integer. Consider: System.out.print ("Enter the number of hours worked: "); hours = Integer.parseInt (in.readLine()); // parseInt is a static method of the Integer wrapper class used to convert String input to int. System.out.print ("Enter pay rate per hour: "); rate = Double.parseDouble (in.readLine()); // ditto for parseDouble – a static method (class method) for the Double wrapper class. © 2004 Pearson Addison-Wesley. All rights reserved 2-29 Continuing… • System.out.println (); pay = hours * rate; NumberFormat fmt = NumberFormat.getCurrencyInstance(); // Whoa! NumberFormat is a class!!! // fmt is a ‘formatter object’ returned by the static class, getCurrencyInstance(). // This formatter object, fmt, returned by getCurrencyInstance() has a method // we will use, namely ‘format.’ See below. System.out.println (name + ", your pay is: " + fmt.format(pay)); }// end main } // end Wages2 So, we need to discuss NumberFormat and DecimalFormat classes. But first: another example related to your programming assignment. © 2004 Pearson Addison-Wesley. All rights reserved 2-30 Example. (Includes Javadoc info.) /** Program #2 Bob Roggio COP 2551 * Fall 2005 *Purpose: Gain experience in using several arithmetic operators, *interactive programming (prompts and inputs), and experience using stream *input using BufferedReader class. To accomplish using the BufferedReader *class, we must import java.io package and java text.NumberFormat class. *Also, This program introduces javadoc for programming documentation. *Program will be submitted using shar (program file plus javadoc file) and *turnin facility. * To generate javadoc documentation, issue: $ javadoc programName <enter> * (no need to include .java on the programName) * Remove all generated files except the .html file, as programName.html */ // end Javadoc information import java.io.*; import java.text.NumberFormat; <program code follows….> © 2004 Pearson Addison-Wesley. All rights reserved 2-31 Snippets from My Program public class Computation { public static void main (String [ ] args) throws IOException { // Declarations int odometerBefore, odometerAfter, odometerDifference; float gallonsUsed, mpg; int kilometersBefore, kilometersAfter, kilometersDifference; float litersUsed, kilometersPerLiter; String name; // Get input from client BufferedReader in = new BufferedReader (new InputStreamReader (System.in)); © 2004 Pearson Addison-Wesley. All rights reserved 2-32 Snippets from My Program // Creates standard input stream object, in, in useful form // Name of input stream object is 'in'. Is an object of type BufferedReader. // Creates an input stream that treats input as characters and buffers the // input so it can be read one line at a time. // prompt user for inputs System.out.print ("Enter your name: "); name = in.readLine(); System.out.println ("\n\nWelcome, " + name + "\n"); // Prompt Client for Inputs System.out.print ("Enter the beginning integer odometer reading, please.\t "); odometerBefore = Integer.parseInt (in.readLine()); System.out.print ("Enter the ending odometer reading, please.\t "); <you obtain the odometer reading at the end – as above> © 2004 Pearson Addison-Wesley. All rights reserved 2-33 Snippets from My Program <continuing using the same technique: Wrapper classes for primitives…> System.out.print ("Enter the fuel used in fractions of a gallon, such as 6.2: "); gallonsUsed = Float.parseFloat(in.readLine()); // Output (Echo Inputs) the Inputs System.out.println ("\nStarting Odometer Reading (miles) " + " "+" Ending Odometer Reading (miles) “ + "\t Fuel Consumed (gal) "); etc….. // Perform Computations odometerDifference = odometerAfter - odometerBefore; mpg = odometerDifference/gallonsUsed; etc. © 2004 Pearson Addison-Wesley. All rights reserved 2-34 Formatting Output (see Chap 3) • Remember: some classes contain static (class) methods (and attributes too). (more later in course) • The NumberFormat class (in java.text package) has several static methods; Two of these static methods ‘return’ a ‘formatter object’ of type NumberClass as NumberFormat money = NumberFormat.getCurrencyInstance(); and NumberFormat percent = NumberFormat.getPercentInstance(); Since ‘money’ is an object of type NumberFormat, it ‘gets’ everything in NumberFormat, including a format method – see book. • This format method is invoked through a formatter object (money.format(argument) ) and returns a String (see chap 3…) that contains the number formatted in the appropriate manner. • Many more examples in book. © 2004 Pearson Addison-Wesley. All rights reserved 2-35 More…Stated a little differently… • We have requested a special kind of object from one of NumberFormat’s static methods (getCurrencyInstance) Two such static methods from which we can request objects are getCurrencyInstance and getPercentInstance(). • These methods, when invoked, return a special kind of object – called a ‘formatter’ object. When such an object is called using its ‘format’ method the argument is formatted appropriately (getCurrencyInstance() produces an output that looks like dollars and cents; getPercentInstance() produces an output with a % sign. These objects use the ‘format’ method defined in class NumberFormat, since each of these formatter objects “is_a” NumberFormat object. (Inheritance) © 2004 Pearson Addison-Wesley. All rights reserved 2-36 // Price.java Author: Lewis/Loftus import java.text.NumberFormat; public class Price { public static void main (String[] args) // purged comments for space….. { final double TAX_RATE = 0.06; // 6% sales tax int quantity; double subtotal, tax, totalCost, unitPrice; System.out.print ("Enter the quantity: "); quantity = Keyboard.readInt(); // we will use BufferedReader object ‘in’ ….. System.out.print ("Enter the unit price: "); unitPrice = Keyboard.readDouble(); // we will use BufferedReader and Double wrapper class… subtotal = quantity * unitPrice; tax = subtotal * TAX_RATE; totalCost = subtotal + tax; // Want to print output (subtotals, tax, TaxRate, and totalCost) with appropriate formatting SO: NumberFormat fmt1 = NumberFormat.getCurrencyInstance(); // returns an object – a ‘formatter’ obj NumberFormat fmt2 = NumberFormat.getPercentInstance(); // returns an object – a ‘formatter’ obj // fmt1 and fmt2 are each objects of type NumberFormat and each have the method ‘format’ to // perform formatting…..Their responsibilities are to format currency or percentages respective 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)); } // end main } // end Price class © 2004 Pearson Addison-Wesley. All rights reserved 2-37 More on Formatting Output • The DecimalFormat class can be used to format a floating point value in generic ways For example, you can specify that the number should be printed to three decimal places Unlike the NumberFormat class with its static methods, the use of DecimalFormat requires instantiating objects in the usual way. • The constructor of the DecimalFormat class takes a string that represents a pattern for the formatted number. (Means, when the object is created, it is given an initial value by the Constructor, and this value is an alphanumeric ‘pattern.’) • These ‘patterns’ can be quite involved. © 2004 Pearson Addison-Wesley. All rights reserved 2-38 //******************************************************************** // CircleStats.java Author: Lewis/Loftus import cs1.Keyboard; import java.text.DecimalFormat; public class CircleStats { //----------------------------------------------------------------// Calculates the area and circumference of a circle given its // radius. //----------------------------------------------------------------public static void main (String[] args) { int radius; double area, circumference; System.out.print ("Enter the circle's radius: "); radius = Keyboard.readInt(); // we will use BufferedReader objects… and Wrappers… area = Math.PI * Math.pow(radius, 2); //look at the static Math attributes and methods! circumference = 2 * Math.PI * radius; // Round the output to three decimal places DecimalFormat fmt = new DecimalFormat ("0.###"); //fmt is an object of type DecimalFormat // string 0.### indicates that at least one digit should be to the left of the decimal, and // should be a zero if the integer position of the value is zero. Also indicates that the // fractional part should be rounded to three digits. System.out.println ("The circle's area: " + fmt.format(area)); //Where did this ‘format’ come from??? System.out.println ("The circle's circumference: “ + fmt.format(circumference)); // end main ©}2004 Pearson Addison-Wesley. All rights reserved 2-39 } // end CircleStats Outline Character Strings Variables and Assignment Primitive Data Types Expressions Intro to Objects Interactive Programs Data Conversion Graphics Applets Drawing Shapes © 2004 Pearson Addison-Wesley. All rights reserved 2-40 Data Conversion • Sometimes it is convenient to convert data from one type to another • For example, in a particular situation we may want to treat an integer as a floating point value • These conversions do not change the type of a variable or the value that's stored in it – they only convert a value as part of a computation © 2004 Pearson Addison-Wesley. All rights reserved 2-41 Data Conversion • Conversions must be handled carefully to avoid losing information • Widening conversions are safest because they tend to go from a small data type to a larger one (such as a short to an int) • Narrowing conversions can lose information because they tend to go from a large data type to a smaller one (such as an int to a short) • In Java, data conversions can occur in three ways: assignment conversion promotion casting © 2004 Pearson Addison-Wesley. All rights reserved 2-42 Assignment Conversion • Assignment conversion occurs when a value of one type is assigned to a variable of another • If money is a float variable and dollars is an int variable, the following assignment converts the value in dollars to a float money = dollars • Only widening conversions can happen via assignment (I do NOT believe this to be true!) • Note that the value or type of dollars did not change © 2004 Pearson Addison-Wesley. All rights reserved 2-43 Data Conversion • Promotion happens automatically when operators in expressions convert their operands • For example, if sum is a float and count is an int, the value of count is converted to a floating point value to perform the following calculation: result = sum / count; © 2004 Pearson Addison-Wesley. All rights reserved 2-44 Casting • Casting is the most powerful, and dangerous, technique for conversion • To cast, the type is put in parentheses in front of the value being converted • For example, if total and count are integers, but we want a floating point result when dividing them, we can cast total: result = (float) total / count; © 2004 Pearson Addison-Wesley. All rights reserved 2-45 Outline Character Strings Variables and Assignment Primitive Data Types Expressions Interactive Programs Data Conversion Graphics Applets Drawing Shapes © 2004 Pearson Addison-Wesley. All rights reserved 2-46 Introduction to Graphics • The last few sections of each chapter of the textbook focus on graphics and graphical user interfaces • A picture or drawing must be digitized for storage on a computer • A picture is made up of pixels (picture elements), and each pixel is stored separately • The number of pixels used to represent a picture is called the picture resolution • The number of pixels that can be displayed by a monitor is called the monitor resolution © 2004 Pearson Addison-Wesley. All rights reserved 2-47 Coordinate Systems • Each pixel can be identified using a twodimensional coordinate system • When referring to a pixel in a Java program, we use a coordinate system with the origin in the topleft corner (0, 0) 112 X 40 (112, 40) Y © 2004 Pearson Addison-Wesley. All rights reserved 2-48 Representing Color • A black and white picture could be stored using one bit per pixel (0 = white and 1 = black) • A colored picture requires more information; there are several techniques for representing colors • For example, every color can be represented as a mixture of the three additive primary colors Red, Green, and Blue • Each color is represented by three numbers between 0 and 255 that collectively are called an RGB value © 2004 Pearson Addison-Wesley. All rights reserved 2-49 The Color Class • A color in a Java program is represented as an object created from the Color class • The Color class also contains several predefined colors, including the following: Object RGB Value Color.black Color.blue Color.cyan Color.orange Color.white Color.yellow 0, 0, 0 0, 0, 255 0, 255, 255 255, 200, 0 255, 255, 255 255, 255, 0 © 2004 Pearson Addison-Wesley. All rights reserved 2-50 Outline Character Strings Variables and Assignment Primitive Data Types Expressions Data Conversion Interactive Programs Graphics Applets Drawing Shapes © 2004 Pearson Addison-Wesley. All rights reserved 2-51 Applets • A Java application is a stand-alone program with a main method (like the ones we've seen so far) • A Java applet is a program that is intended to transported over the Web and executed using a web browser • An applet also can be executed using the appletviewer tool of the Java Software Development Kit • An applet doesn't have a main method • Instead, there are several special methods that serve specific purposes © 2004 Pearson Addison-Wesley. All rights reserved 2-52 Applets • The paint method, for instance, is executed automatically and is used to draw the applet’s contents • The paint method accepts a parameter that is an object of the Graphics class • A Graphics object defines a graphics context on which we can draw shapes and text • The Graphics class has several methods for drawing shapes © 2004 Pearson Addison-Wesley. All rights reserved 2-53 Applets • The class that defines an applet extends the Applet class • This makes use of inheritance, which is explored in more detail in Chapter 8 • See Einstein.java (page 97) © 2004 Pearson Addison-Wesley. All rights reserved 2-54 //******************************************************************** // Einstein.java Author: Lewis/Loftus // // Demonstrates a basic applet. //******************************************************************** import javax.swing.JApplet; import java.awt.*; public class Einstein extends JApplet { //----------------------------------------------------------------// Draws a quotation by Albert Einstein among some shapes. //----------------------------------------------------------------public void paint (Graphics page) { page.drawRect (50, 50, 40, 40); // square page.drawRect (60, 80, 225, 30); // rectangle page.drawOval (75, 65, 20, 20); // circle page.drawLine (35, 60, 100, 120); // line page.drawString ("Out of clutter, find simplicity.", 110, 70); page.drawString ("-- Albert Einstein", 130, 100); } © 2004 Pearson Addison-Wesley. All rights reserved } 2-55 • An applet is embedded into an HTML file using a tag that references the bytecode file of the applet • The bytecode version of the program is transported across the web and executed by a Java interpreter that is part of the browser © 2004 Pearson Addison-Wesley. All rights reserved 2-56 The HTML applet Tag <html> <head> <title>The Einstein Applet</title> </head> <body> <applet code="Einstein.class" width=350 height=175> </applet> </body> </html> © 2004 Pearson Addison-Wesley. All rights reserved 2-57 Outline Character Strings Variables and Assignment Primitive Data Types Expressions Data Conversion Interactive Programs Graphics Applets Drawing Shapes © 2004 Pearson Addison-Wesley. All rights reserved 2-58 Drawing Shapes • Let's explore some of the methods of the Graphics class that draw shapes in more detail • A shape can be filled or unfilled, depending on which method is invoked • The method parameters specify coordinates and sizes • Shapes with curves, like an oval, are usually drawn by specifying the shape’s bounding rectangle • An arc can be thought of as a section of an oval © 2004 Pearson Addison-Wesley. All rights reserved 2-59 Drawing a Line 10 150 X 20 45 Y page.drawLine (10, 20, 150, 45); or page.drawLine (150, 45, 10, 20); © 2004 Pearson Addison-Wesley. All rights reserved 2-60 Drawing a Rectangle 50 X 20 40 100 Y page.drawRect (50, 20, 100, 40); © 2004 Pearson Addison-Wesley. All rights reserved 2-61 Drawing an Oval 175 X 20 80 bounding rectangle 50 Y page.drawOval (175, 20, 50, 80); © 2004 Pearson Addison-Wesley. All rights reserved 2-62 Drawing Shapes • Every drawing surface has a background color • Every graphics context has a current foreground color • Both can be set explicitly • See Snowman.java (page103) © 2004 Pearson Addison-Wesley. All rights reserved 2-63 // Snowman.java Author: Lewis/Loftus // Demonstrates basic drawing methods and the use of color. import javax.swing.JApplet; import java.awt.*; public class Snowman extends JApplet { // Draws a snowman. public void paint (Graphics page) { final int MID = 150; final int TOP = 50; setBackground (Color.cyan); page.setColor (Color.blue); page.fillRect (0, 175, 300, 50); // ground page.setColor (Color.yellow); page.fillOval (-40, -40, 80, 80); // sun page.setColor (Color.white); page.fillOval (MID-20, TOP, 40, 40); // head page.fillOval (MID-35, TOP+35, 70, 50); // upper torso page.fillOval (MID-50, TOP+80, 100, 60); // lower torso page.setColor (Color.black); page.fillOval (MID-10, TOP+10, 5, 5); // left eye page.fillOval (MID+5, TOP+10, 5, 5); // right eye page.drawArc (MID-10, TOP+20, 20, 10, 190, 160); // smile page.drawLine (MID-25, TOP+60, MID-50, TOP+40); // left arm page.drawLine (MID+25, TOP+60, MID+55, TOP+60); // right arm page.drawLine (MID-20, TOP+5, MID+20, TOP+5); // brim of hat page.fillRect (MID-15, TOP-20, 30, 25); // top of hat © }2004 Pearson Addison-Wesley. All rights reserved } 2-64 Summary • Chapter 2.2 focused on: expressions and operator precedence brief introduction to objects (out of place – chap 3) accepting input from the user – using Buffered Reader Data conversions Wrapper classes Java applets Introduction to graphics © 2004 Pearson Addison-Wesley. All rights reserved 2-65