1 / 21

Methods that return values

Methods that return values. suggested reading: 3.2. Java's Math class. Java has a class called Math that has several useful static methods to perform mathematical calculations. Methods that "return". The Math methods are called by writing: Math. <method name> ( <parameters> );

marioni
Download Presentation

Methods that return values

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. Methods that return values suggested reading: 3.2

  2. Java's Math class • Java has a class called Math that has several useful static methods to perform mathematical calculations.

  3. Methods that "return" • The Math methods are called by writing:Math. <method name> (<parameters> ); • The methods of the Math class do not print their results to the console. • Instead, a call to one of these methods can be used as an expression or part of an expression. • Each method evaluates to produce (or return) a numeric result. • The result can be printed or used in a larger expression. • Example: 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

  4. Math method 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?

  5. Methods that return values • Declaring a method that returns a value: public static <type><name> ( <parameters> ) { <statements> ; } • Returning a value from a method: return <expression> ; • Example: // Returns the given number cubed (to the third power). public static int cube(int number) { return number * number * number; }

  6. Example returning methods // Converts Fahrenheit to Celsius. public static double fToC(double degreesF) { return 5.0 / 9.0 * (degreesF - 32); } // Rounds the given number to the given number of decimal places. // Example: round(3.14159265, 4) returns 3.1416. public static double round(double value, int places) { double pow = Math.pow(10, places); value = value * pow; // upscale the number value = Math.round(value); // round to nearest whole number value = value / pow; // downscale the number return value; }

  7. Return questions • Write a method named area that accepts a circle's radius as a parameter and returns the area of the circle. • You may wish to use the constant Math.PI in your solution. • 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 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.

  8. How to comment: methods 2 • If your method accepts parameters and/or returns a value, write a brief description of what the parameters are used for and what kind of value will be returned. • In your comments, you can also write your assumptions about the values of the parameters. • You may wish to give examples of what values your method returns for various input parameter values. • Example: // This method returns the factorial of the given integer n. // The factorial is the product of all integers up to that number. // Assumes that the parameter value is non-negative. // Example: factorial(5) returns 1 * 2 * 3 * 4 * 5 = 120. public static int factorial(int n) { ... }

  9. Using Objects (in brief) suggested reading: 3.3

  10. Objects • So far, we have seen: • methods, which represent behavior • variables, which represent data (categorized by types) • In Java and other "object-oriented" programming languages, it is possible to create new types that are combinations of the existing types. • Such types are called object types or reference types. • In this chapter we will learn how to use certain objects that exist in Java. • In Chapter 8 we will learn to create our own types of objects.

  11. Objects and classes • object: An entity that contains data and behavior. • There are variables inside the object, representing its data. • There are methods inside the object, representing its behavior. • class: • A program, or... • A type of objects. • Examples: • The class named String represents objects that hold text characters. • The class named Point represents objects that hold (x, y) data. • The class named Scanner represents objects that read information from the keyboard, files, and other sources.

  12. Constructing objects • construct: To create a new object. • Objects are constructed with the new keyword. • Most objects must be constructed before they can be used. • Constructing objects, general syntax: <type><name> = new <type>(<parameters>); • Examples: Point p = new Point(7, -4); DrawingPanel window = new DrawingPanel(300, 200); Color orange = new Color(255, 128, 0); • Classes' names are usually uppercase (e.g. Point, Color). • Strings are also objects but are constructed without new : String name = "Kelly T. Heffner";

  13. Calling methods of objects • Objects contain methods that can be called by your program. • A String's methods manipulate or process the String in useful ways. • When we call an object's method, we are sending a message to it. • We don't just write the method's name; we also have to specify which object we are talking to. • Calling a method of an object, general syntax: <variable> . <method name> ( <parameters> ) • The results will be different from one object to another. • Examples: String name = "Kelly T. Heffner"; System.out.println(name.length()); // 16 Point p1 = new Point(3, 4); Point p2 = new Point(0, 0); System.out.println(p1.distance(p2)); // 5.0

  14. Interactive Programs Using Scanner Objects suggested reading: 3.4

  15. Interactive programs • We have written several programs that print output to the console. • It is also possible to read text input from the console. • The user running the program types the input into the console. • We can capture the input and use it as data in our program. • A program that processes input from the user is called an interactive program. • Interactive programs can be challenging: • Computers and users think in very different ways. • Users tend to misbehave.

  16. Input and System.in • When we print text output to the console, we communicate with an object named System.out . • We call the println (or print) method of System.out to print a message to the console. • The object that holds the user's console input is named System.in . • System.in is not intended to be used directly. • Instead, we will use a second object of a type named Scanner to help read data from System.in. • We will construct a Scanner object and pass System.in as a parameter to it. • We can then ask the Scanner to read various kinds of input from the console.

  17. Scanner • Constructing a Scanner object to read console input: Scanner <name> = new Scanner(System.in); • Example: Scanner console = new Scanner(System.in); • Java class libraries: The objects available to you as part of Java. • These objects are organized into groups named packages. • To use the objects from a package, you must include an import statement at the top of your program. • To use Scanner, put this at the start of your program: import java.util.*;

  18. Scanner methods • Methods of Scanner that we will use in this chapter: • Each of these methods causes your program to pause until the user has typed input and pressed Enter, then it returnsthe typed value to your program. • token: A unit of user input, as read by the Scanner. • Tokens are separated by whitespace (spaces, tabs, new lines). • How many tokens appear on the following line of input? 23 John Smith 42.0 "Hello world"

  19. Example Scanner usage import java.util.*; // so that I can use Scanner public class ReadSomeInput { public static void main(String[] args) { Scanner console = new Scanner(System.in); System.out.print("What is your first name? "); String name = console.next(); System.out.print("And how old are you? "); int age = console.nextInt(); System.out.println(name + " is " + age); System.out.println("That's quite old!"); } } • Output (user input underlined): What is your first name? Marty How old are you? 14 Marty is 14 That's quite old!

  20. Scanners as parameters • If multiple methods read user input from the keyboard, you should declare a Scanner in main and pass it to each of them as a parameter. • In this way, all of the methods can share the same Scanner object to read keyboard input. public static void main(String[] args) { Scanner console = new Scanner(System.in); int sum = readSum3(console); System.out.println("The sum is " + sum); } public static int readSum3(Scanner console) { System.out.print("Type 3 numbers: "); int num1 = console.nextInt(); int num2 = console.nextInt(); int num3 = console.nextInt(); return num1 + num2 + num3; }

  21. Scanner question A person's body mass index (BMI) is computed by the following formula: • Write a program that produces the following output: This program reads in data for two people and computes their body mass index (BMI) and weight status. Enter next person's information: height (in inches)? 62.5 weight (in pounds)? 130.5 Enter next person's information: height (in inches)? 58.5 weight (in pounds)? 90 Person #1 body mass index = 23.485824 Person #2 body mass index = 18.487836949375414 Difference = 4.997987050624587

More Related