Presentation is loading. Please wait.

Presentation is loading. Please wait.

Building Java Programs

Similar presentations


Presentation on theme: "Building Java Programs"— Presentation transcript:

1 Building Java Programs
Chapter 3 Lecture 3-2: Return; doubles and casting reading: 3.2, 4.1 videos: Ch. 3 #2

2 Lecture outline Finish Car example Returns Casting (if time)
Java Math library (using methods that return values) Writing methods that return values Casting (if time)

3 Parameterized figures
Modify the car-drawing method so that it can draw cars at different positions, as in the following image. Top-left corners: (10, 30), (150, 10)

4 Parameterized answer import java.awt.*; public class Car3 { public static void main(String[] args) { DrawingPanel panel = new DrawingPanel(260, 100); panel.setBackground(Color.LIGHT_GRAY); Graphics g = panel.getGraphics(); drawCar(g, 10, 30); drawCar(g, 150, 10); } public static void drawCar(Graphics g, int x, int y) { g.setColor(Color.BLACK); g.fillRect(x, y, 100, 50); g.setColor(Color.RED); g.fillOval(x + 10, y + 40, 20, 20); g.fillOval(x + 70, y + 40, 20, 20); g.setColor(Color.CYAN); g.fillRect(x + 70, y + 10, 30, 20);

5 Drawing parameter question
Then modify drawCar so the car can be drawn at any size. Existing car: size 100 Second car: size 50, top/left at (150, 10)

6 Drawing parameter answer
import java.awt.*; public class Car4 { public static void main(String[] args) { DrawingPanel panel = new DrawingPanel(210, 100); panel.setBackground(Color.LIGHT_GRAY); Graphics g = panel.getGraphics(); drawCar(g, 10, 30, 100); drawCar(g, 150, 10, 50); } public static void drawCar(Graphics g, int x, int y, int size) { g.setColor(Color.BLACK); g.fillRect(x, y, size, size / 2); g.setColor(Color.RED); g.fillOval(x + size / 10, y + 2 * size / 5, size / 5, size / 5); g.fillOval(x + 7 * size / 10, y + 2 * size / 5, g.setColor(Color.CYAN); g.fillRect(x + 7 * size / 10, y + size / 10, 3 * size / 10, size / 5);

7 Loops that begin at 0 Beginning at 0 and using < can make coordinates easier. Use a for loop to draw a line of cars. Start at (10, 130), each car size 40, separated by 50px.

8 Looping answer import java.awt.*; public class Car5 { public static void main(String[] args) { DrawingPanel panel = new DrawingPanel(210, 100); panel.setBackground(Color.LIGHT_GRAY); Graphics g = panel.getGraphics(); drawCar(g, 10, 30, 100); drawCar(g, 150, 10, 50); for (int i = 0; i < 5; i++) { drawCar(g, 10 + i * 50, 130, 40); } public static void drawCar(Graphics g, int x, int y, int size) { g.setColor(Color.BLACK); g.fillRect(x, y, size, size / 2); g.setColor(Color.RED); g.fillOval(x + size / 10, y + 2 * size / 5, size / 5, size / 5); g.fillOval(x + 7 * size / 10, y + 2 * size / 5, g.setColor(Color.CYAN); g.fillRect(x + 7 * size / 10, y + size / 10, 3 * size / 10, size / 5);

9 Drawing w/ loops questions
Draw ten stacked rectangles starting at (20, 20), height 10, width starting at 100 and decreasing by 10 each time: DrawingPanel panel = new DrawingPanel(160, 160); Graphics g = panel.getGraphics(); for (int i = 0; i < 10; i++) { g.drawRect(20, * i, * i, 10); }

10 reading: 3.2 self-check: #7-11 exercises: #4-6 videos: Ch. 3 #2
Return Values reading: 3.2 self-check: #7-11 exercises: #4-6 videos: Ch. 3 #2

11 Java's Math class Method name Description Math.abs(value)
absolute value Math.round(value) nearest whole number Math.ceil(value) rounds up Math.floor(value) rounds down Math.log10(value) logarithm, base 10 Math.max(value1, value2) larger of two values Math.min(value1, value2) smaller of two values Math.pow(base, exp) base to the exp power Math.sqrt(value) square root Math.sin(value) Math.cos(value) Math.tan(value) sine/cosine/tangent of an angle in radians Math.toDegrees(value) Math.toRadians(value) convert degrees to radians and back Math.random() random double between 0 and 1 Constant Description E PI

12 Calling Math methods Examples:
Math.methodName(parameters) Examples: double squareRoot = Math.sqrt(121.0); System.out.println(squareRoot); // 11.0 int absoluteValue = Math.abs(-50); System.out.println(absoluteValue); // 50 System.out.println(Math.min(3, 7) + 2); // 5 The Math methods do not print to the console. Each method produces ("returns") a numeric result. The results are used as expressions (printed, stored, etc.).

13 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. main Math.abs(-42) -42 Math.round(2.71) 2.71 42 3

14 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( ) 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?

15 Returning a value Example: statements; ... return expression;
public static type name(parameters) { statements; ... return expression; } Example: // Returns the slope of the line between the given points. public static double slope(int x1, int y1, int x2, int y2) { double dy = y2 - y1; double dx = x2 - x1; return dy / dx;

16 Return examples // Converts Fahrenheit to Celsius. public static double fToC(double degreesF) { double degreesC = 5.0 / 9.0 * (degreesF - 32); return degreesC; } // 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: return 5.0 / 9.0 * (degreesF - 32);

17 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 x1, int x2, int y1, int y2) { double dy = y2 - y1; double dx = x2 - x1; double result = dy / dx; return result; }

18 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 ourSlope = slope(0, 0, 6, 3); System.out.println("The slope is " + ourSlope); } public static double slope(int x1, int x2, int y1, int y2) { double dy = y2 - y1; double dx = x2 - x1; double result = dy / dx; return result;

19 Quirks of real numbers Some Math methods return double or other non-int types. int x = Math.pow(10, 3); // ERROR: incompat. types Some double values print poorly (too many digits). double result = 1.0 / 3.0; System.out.println(result); // The computer represents doubles in an imprecise way. System.out.println( ); Instead of 0.3, the output is

20 Type casting type cast: A conversion from one type to another. Syntax:
To promote an int 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; // 3.8 int result2 = (int) result; // 3 int x = (int) Math.pow(10, 3); // 1000

21 More about type casting
Type casting has high precedence and only casts the item immediately next to it. double x = (double) / 2; // 1 double y = 1 + (double) 1 / 2; // 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;

22 Return questions Write a method named area that accepts a circle's radius as a parameter and returns its area. You may wish to use the constant Math.PI in your solution. Write a method named attendance that accepts a number of lectures attended by a student, and returns how many points a student receives for attendance. The student receives 2 points for each of the first 5 lectures and 1 point for each subsequent lecture.

23 Return questions 2 Write a method named distanceFromOrigin that accepts x and y coordinates as parameters and returns the distance between that (x, y) point and the origin. Write a method named medianOf3 that accepts 3 integers as parameters and returns the middle value. For example, medianOf3(4, 2, 7) should return 4. Hint: Use methods from the Math class in your solution.


Download ppt "Building Java Programs"

Similar presentations


Ads by Google