Building Java Programs Chapter 3 Lecture 3 2
Building Java Programs Chapter 3 Lecture 3 -2: More Graphics, return values, Math, and casting reading: Supplement 3 G, 3. 2, 2. 1 - 2. 2
Java book figure Write a program that draws the following figure: drawing panel is size 200 x 150 book is at (20, 35), size 100 x 100 cyan background white "BJP" text at position (70, 55) stairs are (red=191, green=118, blue=73) each stair is 9 px tall 1 st stair is 10 px wide 2 nd stair is 20 px wide. . . stairs are 10 px apart (1 blank pixel between) 2
Java book solution // Draws a Building Java Programs textbook with Drawing. Panel. import java. awt. *; public class Book { public static void main(String[] args) { Drawing. Panel panel = new Drawing. Panel(200, 150); panel. set. Background(Color. WHITE); Graphics g = panel. get. Graphics(); g. set. Color(Color. CYAN); g. fill. Rect(20, 35, 100); // cyan background g. set. Color(Color. WHITE); g. draw. String("BJP", 70, 55); // white "bjp" text g. set. Color(new Color(191, 118, 73)); for (int i = 0; i < 10; i++) { // orange "bricks" g. fill. Rect(20, 35 + 10 * i, 10 + 10 * i, 9); } } } 3
Multiple Java books Modify the Java book program so that it can draw books at different positions as shown below. book top/left positions: (20, 35), (150, 70), (300, 10) drawing panel's new size: 450 x 180 4
Multiple books solution // Draws many BJP textbooks using parameters. import java. awt. *; public class Book 2 { public static void main(String[] args) { Drawing. Panel panel = new Drawing. Panel(450, 180); panel. set. Background(Color. WHITE); Graphics g = panel. get. Graphics(); // draw three books at different locations draw. Book(g, 20, 35); draw. Book(g, 150, 70); draw. Book(g, 300, 10); }. . . 5
Multiple books, cont'd. . // Draws a BJP textbook at the given x/y position. public static void draw. Book(Graphics g, int x, int y) { g. set. Color(Color. CYAN); // cyan background g. fill. Rect(x, y, 100); g. set. Color(Color. WHITE); // white "bjp" text g. draw. String("BJP", x + 50, y + 20); g. set. Color(new Color(191, 118, 73)); for (int i = 0; i < 10; i++) { // orange "bricks" g. fill. Rect(x, y + 10 * i, 10 * (i + 1), 9); } } } 6
Resizable Java books Modify the Java book program so that it can draw books at different sizes as shown below. book sizes: 100 x 100, 60 x 60, 200 x 200 drawing panel's new size: 520 x 240 7
Resizable books solution // Draws many sized BJP textbooks using parameters. import java. awt. *; public class Book 3 { public static void main(String[] args) { Drawing. Panel panel = new Drawing. Panel(520, 240); panel. set. Background(Color. WHITE); Graphics g = panel. get. Graphics(); // draw three books at different locations/sizes draw. Book(g, 20, 35, 100); draw. Book(g, 150, 70, 60); draw. Book(g, 300, 10, 200); }. . . 8
Resizable solution, cont'd. . // Draws a book of the given size at the given position. public static void draw. Book(Graphics g, int x, int y, int size) { g. set. Color(Color. CYAN); g. fill. Rect(x, y, size); // cyan background g. set. Color(Color. WHITE); // white "bjp" text g. draw. String("BJP", x + size/2, y + size/5); g. set. Color(new Color(191, 118, 73)); for (int i = 0; i < 10; i++) { // g. fill. Rect(x, // y + size/10 * i, // size/10 * (i + 1), // size/10 - 1); // } orange "bricks" x y width height } } 9
Return values, Math, and casting reading: 3. 2, 2. 1 - 2. 2 10
Java's Math class Method name Math. abs(value) Description Math. ceil(value) rounds up Math. floor(value) rounds down Math. log 10(value) logarithm, base 10 Math. max(value 1, value 2) larger of two values Math. min(value 1, value 2) smaller of two values Math. pow(base, exp) Math. random() base to the exp power random double between 0 and 1 Math. round(value) nearest whole number Math. sqrt(value) square root Math. sin(value) Math. cos(value) Math. tan(value) sine/cosine/tangent of an angle in radians Math. to. Degrees(value) Math. to. Radians(value) convert degrees to radians and back absolute value Constant Description Math. E 2. 7182818. . . Math. PI 3. 1415926. . . 11
Calling Math methods Math. method. Name(parameters) Examples: double square. Root = Math. sqrt(121. 0); System. out. println(square. Root); // 11. 0 int absolute. Value = Math. abs(-50); System. out. println(absolute. Value); // 50 System. out. println(Math. min(3, 7) + 2); // 5 Must import java. util. *; 12
No output? Simply calling these methods produces no visible result. public class Test. Math { public static void main(String[] args) { Math. pow(3, 4); // no output! } } 13
No output! Math method calls use a feature called return values that cause them to be treated as expressions. The program runs the method, computes the answer, and then "replaces" the call with its computed result value. Math. pow(3, 4); 81. 0; // no output To see the result, we must print it or store it in a variable. double result = Math. pow(3, 4); System. out. println(result); // 81. 0 14
Return return: To send out a value as the result of a method. The opposite of a parameter Parameters send information in from the caller to the method. Return values send information out from a method to its caller. A call to the method can be used as part of an expression. Math. abs(-42) -42 42 main 2. 71 3 Math. round(2. 71) 15
Why return and not print? It might seem more useful for the Math methods to print their results rather than returning them. Why don't they? Answer: Returning is more flexible than printing. We can compute several things before printing: double pow 1 = Math. pow(3, 4); double pow 2 = Math. pow(10, 6); System. out. println("Powers are " + pow 1 + " and " + pow 2); We can combine the results of many computations: double k = 13 * Math. pow(3, 4) + 5 - Math. sqrt(17. 8); We might not want to print the result at all: for (int i = 1; i <= Math. min(x, y); i++) {. . . } 16
Math questions Evaluate the following expressions: Math. abs(-1. 23) Math. pow(3, 2) Math. pow(10, -2) Math. sqrt(121. 0) - Math. sqrt(256. 0) Math. round(Math. PI) + Math. round(Math. E) Math. ceil(6. 022) + Math. floor(15. 9994) Math. abs(Math. min(-3, -5)) Math. max and Math. min can be used to bound numbers. Consider an int variable named age. What statement would replace negative ages with 0? What statement would cap the maximum age to 40? 17
Incompatible types Some Math methods return double or other non-int types. int x = Math. pow(10, 3); // ERROR: incompatible types But for the above expression, we know the result will be an integer What if you wanted to store a double in an int variable? 18
Type casting type cast: A conversion from one type to another. To promote an into a double to get exact division from / To truncate a double from a real number to an integer Syntax: (<type>)<expression> Examples: double result = (double) 19 / 5; int result 2 = (int)result; int x = (int)Math. pow(10, 3); // 3. 8 // 3 // 1000 19
More about type casting Type casting has high precedence and only casts the item immediately next to it. double x = (double) 1 + 1 / 2; double y = 1 + (double) 1 / 2; // 1. 0 // 1. 5 You can use parentheses to force evaluation order. double average = (double)(a + b + c) / 3; A conversion to double can be achieved in other ways. double average = 1. 0 * (a + b + c) / 3; 20
Returning a value public static <type> <name>(<parameters>) { <statement(s)>; . . . return <expression>; } Example: // Returns the slope public static double dy = y 2 double dx = x 2 return dy / dx; } of the line between the given points. slope(int x 1, int y 1, int x 2, int y 2) { y 1; x 1; slope(5, 11, 1, 3) returns 2. 0 21
Return examples // Converts degrees Fahrenheit to Celsius. public static double f. To. C(double degrees. F) { double degrees. C = 5. 0 / 9. 0 * (degrees. F - 32); return degrees. C; } // Computes triangle hypotenuse length given its side lengths. public static double hypotenuse(int a, int b) { double c = Math. sqrt(a * a + b * b); return c; } You can shorten the examples by returning an expression: public static double f. To. C(double degrees. F) { return 5. 0 / 9. 0 * (degrees. F - 32); } 22
Common error: Not storing Many students incorrectly think that a return statement sends a variable's name back to the calling method. public static void main(String[] args) { slope(0, 0, 6, 3); System. out. println("The slope is " + result); } // ERROR: result not defined public static double slope(int x 1, int y 1, int x 2, int y 2) { double dy = y 2 - y 1; double dx = x 2 - x 1; double result = dy / dx; return result; } 23
Fixing the common error Instead, returning sends the variable's value back. The returned value must be stored into a variable or used in an expression to be useful to the caller. public static void main(String[] args) { double s = slope(0, 0, 6, 3); System. out. println("The slope is " + s); } public static double slope(int x 1, int y 1, int x 2, int y 2) { double dy = y 2 - y 1; double dx = x 2 - x 1; double result = dy / dx; return result; } 24
Common error variation Particularly confusing is conflating the return variable with a variable in the calling method. Your program will compile, but you won’t get the right result! public class Return. Example { public static void main(String[] args) { int x = 1; add. One(x); System. out. println("x = " + x); } public static int add. One(int x) { x = x + 1; return x; } } 25
Don’t ignore the return value! Just because the return variable in the called method has the same name as the variable in the calling method, they are NOT the same. Think scope! public class Return. Example { public static void main(String[] args) { int x = 1; add. One(x); System. out. println("x = " + x); } public class Return. Example { public static void main(String[] args) { int x = 1; x = add. One(x); System. out. println("x = " + x); } public static int add. One(int x) { x = x + 1; return x; } } 26
Displacement Exercise In physics, the displacement of a moving body represents its change in position over time while accelerating. Given initial velocity v 0 in m/s, acceleration a in m/s 2, and elapsed time t in s, the displacement of the body is: Displacement = v 0 t + ½ a t 2 Write a method displacement that accepts v 0, t, and a and computes and returns the change in position. Example: displacement(3. 0, 4. 0, 5. 0) returns 52. 0 27
Displacement Solution public static double displacement(double v 0, double t, double a) { double d = v 0 * t + 0. 5 * a * Math. pow(t, 2); return d; } 28
Exercise If you drop two balls, which will hit the ground first? Ball 1: Ball 2: height of 600 m, initial velocity = 25 m/sec downward height of 500 m, initial velocity = 15 m/sec downward Write a program that determines how long each ball takes to hit the ground (and draws each ball falling). Total time is based on the force of gravity on each ball. Acceleration due to gravity ≅ 9. 81 m/s 2, downward Displacement = v 0 t + ½ a t 2 29
Ball solution // Simulates the dropping of two balls from various heights. import java. awt. *; public class Balls { public final static int PANEL_HEIGHT = 600; public static void main(String[] args) { Drawing. Panel panel = new Drawing. Panel(600, 600); Graphics g = panel. get. Graphics(); int ball 1 x = 100, int ball 2 x = 200, initial. Ball 1 y = 600, initial. Ball 2 y = 500, v 01 = 25; v 02 = 15; // draw the balls at each time increment for (double t = 0; t <= 10. 0; t = t + 0. 1) { double height 1 = initial. Ball 1 y - displacement(v 01, t, 9. 81); g. fill. Oval(ball 1 x, PANEL_HEIGHT - (int)height 1, 10); double height 2 = initial. Ball 2 y - displacement(v 02, t, 9. 81); g. fill. Oval(ball 2 x, PANEL_HEIGHT - (int)height 2, 10); } } panel. sleep(50); panel. clear(); // pause for 50 ms . . . 30
- Slides: 30