Presentation is loading. Please wait.

Presentation is loading. Please wait.

Methods: Creation and Use Chapters 5 and 6

Similar presentations


Presentation on theme: "Methods: Creation and Use Chapters 5 and 6"— Presentation transcript:

1 Methods: Creation and Use Chapters 5 and 6
Basic Programming Methods: Creation and Use Chapters 5 and 6

2 Outline What are methods? Creating methods other than main
what are they for? what do they look like? how do we use them? what are some useful ones? Creating methods other than main void, parameterless methods void methods with parameters value-returning methods

3 What are Methods? Methods are named bits of code
instructions for carrying out some (small) task main is for doing a whole program other methods not usually a whole program also called procedures, subroutines, functions We have been using them all along main is a method System.out.print and System.out.println are, too so are all the kbd.nextWhatevers

4 What Are Methods For? Most methods do one thing
System.out.print prints what you give it System.out.println prints it and ends the line kbd.nextInt reads an integer value Usually something you want to do many times print lots of things; read lots of numbers Often just one step of an algorithm the low-level details of a high-level step A few other reasons….

5 Calling a Method Telling the computer to do the instructions
to print this thing or read a number or whatever Method calls look like this: location.name(arguments) location (e.g. System.out or kbd) sometimes it can be left off entirely name (e.g. println or nextDouble) may be zero, one or more arguments separated by commas but parentheses are needed, even if no arguments

6 Named Instructions Calling the method makes the computer run those instructions running a console program = calling main Someone wrote instructions for printing saved them in a method called print put that method into System.out call System.out.print = run those instructions Someone wrote instructions for reading an int call kbd.nextInt = run those instructions

7 More Methods Many useful methods have been provided Math methods
find the square root or power, trig functions, … y = Math.sqrt(x); String methods get part of it, find something in it, … // everything before the comma is the person's last name lastName = fullName.substring(0, fullName.indexOf(","));

8 Math Methods Standard functions available using Math
power function: pow System.out.println("5 squared is " + Math.pow(5, 2)); maximum function: max bestScore = Math.max(testScore, examScore); square root: sqrt root = (-b + Math.sqrt(b*b – 4*a*c)) / (2 * a); Same form for all functions Math.functionName(arguments…)

9 Arguments “Arguments” are given to the method
we also say that the method takes arguments Math.sqrt(10) – 10 is the (only) argument sqrt knows how to find the square root of a number but need to tell it what number to find the square root of Math.pow(5, 2) – 5 and 2 are both arguments pow knows how to raise a number to a power but need to tell it what number to raise to what power arguments must be in the right order! Math.pow(2, 5) is 25, not 52

10 Return Values Math methods return values
(some methods don’t) we use the function to get the returned value Math.sqrt(10) returns the square root of 10 Math.pow(2, 5) returns 2 to the 5th power Math.pow(5, 2) returns 5 to the 2nd power Math.sqrt(x) returns the square root of x Name of method == what value is returned

11 Using Return Values Use the function in expressions
you can print it out System.out.println("5 squared is " + Math.pow(5, 2)); you can save the value in a variable bestScore = Math.max(testScore, examScore); you can use it in a larger math expression root = (-b + Math.sqrt(b*b – 4*a*c)) / (2 * a); even as an argument to another Math method x = Math.pow(10, Math.sqrt(5)); // x =

12 Using Return Values Use the function in expressions
return value used in the expression System.out.println("5 squared is " + Math.pow(5, 2)); Math.pow(5, 2) returns 52 = 25.0 System.out.println prints “5 squared is 25.0” root = (-b + Math.sqrt(b*b – 4*a*c)) / (2 * a); suppose a is 1, b is 6 and c is 9 b*b – 4*a*c = 6*6 – 4*1*9 = 36 – 36 = 0 Math.sqrt(0) returns 0.0 root = ( ) / (2*1) = -6.0 / 2.0 = -3.0

13 Some Math Functions Trigonometric functions Other functions
sin(theta), cos(theta), tan(theta) sine, cosine, tangent of an angle (in radians) toDegrees(rad), toRadians(deg) translate between radians and degrees Other functions exp(x), log10(x), log(x), abs(x) ex, log10(x), ln(x),|x|

14 Exercise Write calls to Math functions to find the square root of 7
6 to the 3rd power 10 times the log (base 10) of x the natural log of 10 times x the number of radians equivalent to 45 degrees the sine of 45 degrees

15 More Math Methods Larger & smaller; rounding off
max, min (each takes two numbers) ceil, floor, round (each takes one number) Random number (in range [0,1)) random int dieRoll1 = 1 + (int)(Math.random() * 6); int dieRoll2 = 1 + (int)(Math.random() * 6); int dice = dieRoll1 + dieRoll2; Note: random takes no arguments! That’s fine.

16 Rounding Off Math.round takes a double, returns a long
Math.round(3.0)  3L long is like int, but bigger (up to ~10 quintillion) can’t be saved in an int variable! int rounded = Math.round(3.6); Error: possible loss of precision need to tell Java it’ll be smaller… int rounded = (int)Math.round(3.6); or just work with long variables!

17 Exercise Write these expressions in Java note: use Math.PI for π

18 String Methods Strings have methods, too
int and double don’t String name = "Djenaba, Louise"; get its length: name.length()  15 get part of it: name.substring(0, 4)  "Djen" find part of it: name.indexOf(",")  7 String surname = name.substring(0, name.indexOf(",")); get an UPPER CASE version: surname.toUpperCase()  "DJENABA" NOTE: surname is still "Djenaba" (it doesn’t change)

19 String Positions Position in a String is how many characters from the start of the String "e" is 2 characters from the start of the String after the D and the j "D" is 0 characters from the start "nab" starts 3 characters from the start "a" is 4 characters from the start it finds the first one D j e n a b 1 2 3 4 5 6 7

20 String Positions If it doesn’t exist, you get -1
name.indexOf("x")  -1 If there’s more than one, it finds the first… name.indexOf("a")  4 …but you can tell it to start later in the String name.indexOf("a", 5)  6 the first "a" at/after position 5 D j e n a b 1 2 3 4 5 6 7

21 String Positions Substrings go between the two numbers…
name.substring(0, 4)  "Djen" name.substring(3, 6)  "nab" name.substring(0, 7)  "Djenaba" …or from the number to the end name.substring(2)  "enaba" name.substring(7)  "" D j e n a b 1 2 3 4 5 6 7

22 Argument Types Arguments must be the right type!
Math.pow("fred", true) makes no sense! the two arguments must be numbers doubles are OK: Math.pow(3.7, 1.98) name.indexOf(7) makes no sense! the argument must be a String: name.indexOf("7") There must be the right number of them! Math.pow(5) and Math.pow(1, 2, 3) make no sense! and they must be in the right order

23 Exercise Assume the calls below are correct. What argument type(s) does each method take? Math.getExponent(3400.2) Math.ulp(2.6) Math.scalb(4.5, 2) str.split(":", "one:two:three:four") str.length() thingy.doesItDo("2", 2, 2.0, "to", "too", "two")

24 Return Types Methods can return any kind of value
(or even none) Math.sqrt(10) returns a double value Math.max(3, 5) returns an int value kbd.nextInt() returns an int value kbd.next() returns a String value str.toUpperCase() returns a String value str.indexOf("n") returns an int value

25 Exercise Assuming the code below is correct, what kind of value does each method return? double x, y = 3.2; int n = 42; String name = "Mark"; boolean good; name = name.replaceFirst("a", "o"); x = Math.exp(y); n = Math.getExponent(x); good = (name.equalsIgnoreCase("mork")); No, I haven't mentioned boolean before. Next week.

26 Making a Method We have been making methods all along main is a method
it's the “main” method of a class the method that runs when you run the program main method has instructions in it so will the other methods we make our own methods will be in the same class as main later we will make other classes with their own methods

27 Why Do We Make Methods? Code Re-use Code Hiding (Encapsulation)
Doing “same” thing in multiple places we do a lot of printing! Code Hiding (Encapsulation) Secret Implementation independence Code Abstraction Top-down design

28 How Do Methods Work Instructions written down in one place . . .
Scanner.java, String.java, Math.java, … . . . call comes from some other place MyProg.java, ExamGrades.java, … Computer remembers where it was . . . . . . follows instructions for the method . . . . . . returns to where it left off

29 Flow of Control You ask System.out to print “Hello”
computer stops working on your program (for a moment) & takes “Hello” to the print method the steps of the print method are followed to completion  Hello appears on the screen your program starts up again, right where it left off Recall: Something you send to a method (like “Hello”) is called an argument

30 Flow of Control You ask kbd to get the next int
computer stops working on your program (for a moment) & starts doing the nextInt method the steps of the nextInt method are followed to completion, getting an int from the user that int is brought back to your program your program starts up again, right where it left off, with that int where kbd.nextInt is/was Recall: Something a method sends back to you (like this int) is called a return value

31 Adding Methods to a Program
We’ll redo RectangleArea using methods the version doing input public class RectangleArea { public static void main(String[] args) { // create variables for length, width and area // print an introduction for the user // get length and width of rectangle // calculate the area // report dimensions and area to user }

32 Method Purpose Method has a job to do Method does its job
get an int from the user print a string on the screen translate a temperature in Celsius to Fahrenheit Method does its job how it does its job is not the caller’s business (recall: code hiding) caller should not worry about it (nor have to)

33 Method Design What is the purpose of this method?
need to know what it’s supposed to do be very clear on its job write its job as a javadoc comment put the javadoc comment after the end of main /** * Print the introduction for this program. */ choose a name that reflects that job printIntroduction

34 Method Use Add the method call to main
don’t need a location no location  the method is in this class NetBeans will underline it in red doesn’t know this method (yet!) public class RectangleArea { public static void main(String[] args) { // create variables for length, width and area // print an introduction for the user printIntroduction();

35 Have NetBeans Create the Method
Click on red circle and choose the command Red underlining disappears Scroll down to bottom of class there’s a new method there move its javadoc comment to right above it create method "printIntroduction()" in … private static void printIntroduction() { throw new UnsupportedOperationException(...); }

36 The Method Header Compare first lines of our two methods
public static void main(String[] args) private static void printIntroduction() private instead of public static and void are the same different names empty parentheses instead of whatever that is more about all this later

37 The Method Body We will delete the body NetBeans created
it means: throw a fit because I can’t cope with this actually it’s an exception instead of a fit, but it’s close Replace it with the commands for printing the introduction (same as in class last week) yes, it’s only two lines; that’s fine private static void printIntroduction() { System.out.println("This program calculates …"); System.out.println(); }

38 Run the Program It’s not finished yet, but that’s OK
run the program  call main main calls printIntroduction printIntroduction prints some stuff printIntroduction finished; go back to main main is finished; program ends run: This program calculates the area of a rectangle. BUILD SUCCESSFUL …

39 Next Method: Pause Follow same procedure as before
determine its purpose; write javadoc prompt user to press enter; wait for user to press enter add pause() to main right after printIntroduction() have NetBeans create the method replace its body with the required commands private static void pause() { System.out.print("Press enter …"); kbd.nextLine(); System.out.println(); }

40 Local Variables Problem: pause does not know symbol kbd
it hasn’t been declared Problem: declaring kbd in main does no good main and pause are different methods each has its own variables Declare kbd in pause method private static void pause() { Scanner kbd = new Scanner(System.in); System.out.print("Press enter …"); kbd.nextLine();

41 Run Program Again Make sure what we just did works
main calls printIntroduction which prints stuff main then calls pause which prints stuff and waits for the user to press enter after user presses enter, pause ends, then main ends run: This program calculates the area of a rectangle. Press enter… BUILD SUCCESSFUL …

42 Programming Principles
Top-down design write a high-level description of the program write descriptions of each step involved Modular design pick a part and write the code for it run your program to test the part you coded you might need to add bits and pieces of code (take it out later) in order to call that part

43 Next Method: printReport
Purpose is to report findings to user needs to print length, width and area so it needs to be told those values printReport(length, width, area); those variables need to be created and given values in main, because that’s who’s doing the telling! /** * Report findings to user. Include length, width and area of * the rectangle in the report. */ Recall: the values given to methods are called arguments

44 Add Variables to main Declare the variables and give them values
remember: this is in main just assign values; don’t even care if they’re right Add call to printReport (at correct place) int length, width, area; length = 10; width = 20; area = 42; // report dimensions and area to user printReport(length, width, area);

45 Have NetBeans Create the Method
Same procedure as before Result is a little bit different three variables declared inside the parentheses match the three variables we put in the method call same types; same names same types is important same names is unimportant private static void printReport(int length, int width, int area) { throw new UnsupportedOperationException(...); }

46 Parameters Those variables are called parameters
have to be same type as arguments are names this method will use for the arguments same names as in main is fine but they are different variables get their values from the arguments printReport(10, 20, 42); printReport(int l, int w, int a)  l = 10, w = 20, a = 42 printReport(50, 77, -3); printReport(int l, int w, int a)  l = 50, w = 77, a = -3

47 Method Body Have it print out the report
use names of parameters; not of arguments private static void printReport(int length, int width, int area) { System.out.print("The area of a " + length + "x" + width + " rectangle is " + area + "."); System.out.println(); } private static void printReport(int len, int wid, int ar) { System.out.print("The area of a " + len + "x" + wid + " rectangle is " + ar + "."); System.out.println(); }

48 Parameter Values Parameter values come from the caller
main is the only caller our methods have, yet Do not read a value into a parameter! the parameter already has a value; don’t change it! main already asked the user for length and width main (will have) already calculated the area if printReport asks user for those values… …user will be asked twice for length and width …user will be asked for the area, which is what the user wanted from the program in the first place!

49 Run the Program New method: test it!
NOTE: those are the numbers you gave it they are wrong, but method did what you told it run: This program calculates the area of a rectangle. Press enter… The area of a 10x20 rectangle is 42. BUILD SUCCESSFUL …

50 Not My Job printReport does not check whether the numbers you gave it make sense that is NOT its job its job is just to print the dang report checking the numbers is somebody else’s problem Programming principle: GIGO garbage in; garbage out if you give a method/program the wrong information, it will do the wrong thing it is following its instructions; that is all it can do

51 Next method: calculateArea
Purpose of the method is to calculate the area of a rectangle of a given length and width needs to be given the length and width needs to return the area we will save the result in the variable area // calculate the area area = calculateArea(length, width); get rid of area = 42; have NetBeans create the method for you another small difference

52 Return Types New method has a return type: int replaces the word void
same as data type of area the variable we saved the result in NetBeans figured it out all by itself same as with the parameters says that this method will return an int value programmer must tell it what value to return private static int calculateArea(int length, int width) { throw new UnsupportedOperationException(...); }

53 Returning a Value Area is product of length and width
Problem: area is not recognized it belongs to main, not calculateArea so declare it here… private static int calculateArea(int length, int width) { area = length * width; } private static int calculateArea(int length, int width) { int area; area = length * width; }

54 Returning a Value Still got a problem you haven’t returned the value
need to use a return command private static int calculateArea(int length, int width) { int area; area = length * width; } private static int calculateArea(int length, int width) { int area; area = length * width; return area; }

55 Last Method: readDimension
Recall our steps for reading length and width same three commands, except length/width one assignment command in each part make method to prompt, read, tidy and return System.out.print("Enter the length of the rectangle: "); length = kbd.nextInt(); kbd.nextLine(); System.out.print("Enter the width of the rectangle: "); width = kbd.nextInt();

56 Multiple Calls to a Method
Call once to read length; again to read width need to tell the method what to prompt for method reads one integer value each time and returns one value each time put what it returns into the appropriate variable prompt for length  save length prompt for width  save width length = readDimension("length"); width = readDimension("width");

57 One Method Definition Have NetBeans create the method for one call
other call is to same method, so it’ll be good, too! parameter type matches the argument (a String) name of parameter taken from argument "length"  length "width"  width we will give it a better name (e.g. dimension) private static int readDimension(String length) { throw new UnsupportedOperationException(...); }

58 Method Body Start with the code you'd use in main
just for reading the length some errors to fix up but we know how to do that! private static int readDimension(String dimension) { System.out.print("Enter the length of the rectangle: "); length = kbd.nextInt(); kbd.nextLine(); }

59 Method Body Add kbd and length Add return command
remember, every method needs its own variables Add return command private static int readDimension(String dimension) { Scanner kbd = new Scanner(System.in); int length; System.out.print("Enter the length of the rectangle: "); length = kbd.nextInt(); kbd.nextLine(); return length; }

60 Run the Program Again It will almost work properly! run:
This program calculates the area of a rectangle. Press enter… Enter the length of the rectangle: 10 Enter the length of the rectangle: 20 The area of a 10x20 rectangle is 200. BUILD SUCCESSFUL …

61 Fix the Prompt Argument says which dimension to ask for
include it in the prompt (instead of "length") private static int readDimension(String dimension) { Scanner kbd = new Scanner(System.in); int length; System.out.print("Enter the " + dimension " of the rectangle: "); length = kbd.nextInt(); kbd.nextLine(); return length; }

62 Run the Program Again It works properly! run:
This program calculates the area of a rectangle. Press enter… Enter the length of the rectangle: 10 Enter the width of the rectangle: 20 The area of a 10x20 rectangle is 200. BUILD SUCCESSFUL …

63 Variable Names Note that readDimension returns an int value
it does not decide what to do with that value main decides what to do with that value length = readDimension("…")  save in length width = readDimension("…")  save in width That number named length in readDimension but it doesn’t matter to the computer can call it length, or width, or area, or ludicrous method will still do the same thing but it does matter to other programmers

64 Rename the Variable It’s not just the length any more
it could be length or width variable names should describe their content Let’s call it answer (the user’s answer) ask NetBeans to make the change! double-click any occurrence of length in readDimension select Rename command from Refactor menu type the new name into the box that appears other variables named length not changed no chance of making different changes on different lines

65 Adding More Pauses Add calls to pause after input & report
OK to call a method multiple times public static void main(String[] args) { int length, width, area; printIntroduction(); pause(); length = getDimension("length"); width = getDimension("width"); area = calculateArea(length, width); printReport(length, width, area); } I took out the pseudo-code comments and the blank lines so it would fit on the screen. You should leave them in.

66 Updating the Javadocs Should have been creating javadoc comments as you went along purpose of the method But now we have the program working, we should finalize them document parameters and return values NetBeans will help!

67 Creating Javadocs with NetBeans
Insert a blank line just above method header Type /** on that line and press enter NetBeans fills in a javadoc comment template /** * dimension */ private static int readDimension(String dimension) { /** private static int readDimension(String dimension) { Scanner kbd = new Scanner(System.in); int answer; System.out.print("Enter the length of the rectangle: "); answer = kbd.nextInt(); private static int readDimension(String dimension) { Scanner kbd = new Scanner(System.in); int answer; System.out.print("Enter the length of the rectangle: "); answer = kbd.nextInt(); kbd.nextLine(); private static int readDimension(String dimension) { Scanner kbd = new Scanner(System.in); int answer; System.out.print("Enter the length of the rectangle: "); answer = kbd.nextInt();

68 Filling in the Javadoc Comment
Type the purpose on the second line add more lines as required; add a blank line after Describe every parameter lines) Describe the return value lines) /** * Read one dimension (length or width) of a rectangle. * dimension the name of the dimension to read the user-given value of that dimension */

69 NetBeans’ Navigation Pane
Bottom-left side of IDE window double-click method to jump to its definition hover to see its javadoc remind you in case you forgot what it’s for

70 Methods Summary Many useful methods available Can create our own
Scanners, Strings, Math, … Can create our own private static methods void methods just do something value-returning methods return a value (duh!) type of value returned replaces void arguments saved into parameters use local variables and parameters don’t change parameter values

71 Exercise Write methods to:
print a given line and a blank line after it. “givenˮ means given to the method calculate f(x) where f(x) = 2x3 – 3x + 5. print the sum of three given numbers. sum three given numbers. what’s different from the previous question?

72 Questions


Download ppt "Methods: Creation and Use Chapters 5 and 6"

Similar presentations


Ads by Google