1 / 23

Java Programming: Return Values and Casting

This chapter covers the concepts of return values, using the Java Math library, writing methods that return values, and casting. It also includes examples and exercises for practice.

Download Presentation

Java Programming: Return Values and Casting

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


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

  2. Lecture outline • Finish Car example • Returns • 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 drawCarso 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, size / 5, 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 forloop 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, size / 5, 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, 20 + 10 * i, 100 - 10 * i, 10); }

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

  11. Java's Math class

  12. Calling Math methods 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 Mathmethods do not print to the console. • Each method produces ("returns") a numeric result. • The results are used as expressions (printed, stored, etc.).

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

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

  15. Returning a value public static typename(parameters) { statements; ... returnexpression; } • 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: public static double fToC(double degreesF) { return 5.0 / 9.0 * (degreesF - 32); }

  17. Common error: Not storing • Many students incorrectly think that a returnstatement 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 doubleor 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);// 0.3333333333333 • The computer represents doubles in an imprecise way. System.out.println(0.1 + 0.2); • Instead of 0.3, the output is 0.30000000000000004

  20. Type casting • type cast: A conversion from one type to another. • 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) 1 + 1 / 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.

More Related