Download presentation
Presentation is loading. Please wait.
Published byChrystal Brooke Pearson Modified over 9 years ago
1
Methods Material from Chapters 5 & 6
2
Terminology Method, function, procedure, subroutine all mean approximately the same thing »functions may return values; procedures don’t »methods belong to something; subroutines may not usually more than one term applies (is correct) Java uses methods but I will sometimes call them functions especially if they return a value »like the square root function/method does
3
Using Methods We’ve been using methods from the start print and println are methods (as is printf) nextInt, nextDouble, next, and nextLine, too equals, equalsIgnoreCase, startsWith, and all those other things we can ask a String to do There are also “Math” methods »math functions Java knows about A method is something the computer can do
4
Math Functions Standard functions available using Math power function: pow System.out.println(“5 squared is ” + Math.pow(5, 2)); maximum function: max int max = Math.max(n1, n2); square root: sqrt double root = (-b + Math.sqrt(b*b – 4*a*c)) / (2 * a); Same form for all functions Math.functionName(arguments…)
5
Arguments “Arguments” are given to the method »we also say that the method takes arguments Math.sqrt(10) – 10 is the (only) argument »asks Math for the square root of 10 Math.pow(5, 2) – 5 and 2 are both arguments »asks Math for 5 to the power 2 (i.e. 5 2 ) arguments must be in the right order! »Math.pow(2, 5) is 2 5, not 5 2
6
Return Values Methods return values »(but some 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 5 th power Math.pow(5, 2) returns 5 to the 2 nd power Math.sqrt(x) returns the square root of x Name of method == what value is returned
7
Using Math Functions 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 maxGrade = Math.max(maxGrade, grade); you can use it in a larger math expression root = (-b + Math.sqrt(b*b – 4*a*c)) / (2 * a); »and the argument can be an expression, too!
8
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 5 2 = 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 = (-6 + 0.0) / (2*1) = -6.0 / 2.0 = -3.0
9
Some Math Functions Trigonometric functions sin, cos, tan »each takes an angle (measured in radians) toDegrees, toRadians »toDegrees takes an angle measured in radians, toRadians takes an angle measured in degrees Exponential & logarithmic functions exp, log, sqrt »each takes a number (a double value)
10
Exercise Write calls to Math functions to find the square root of 7 6 to the 3 rd power 10 times the log of x the log of 10 times x the number of radians equivalent to 45 degrees the sine of 45 degrees
11
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.
12
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!
13
Exercise Write these math expressions in Java x 5 – 1 x 5 – 1 y = x – 1 a = πr 2 z = density = mass / volume »rounded to nearest int »mass and volume are doubles
14
Other Methods We’ve Seen For reading data (kbd is a Scanner) kbd.nextInt() kbd.nextDouble() kbd.next() kbd.nextLine() For checking strings (resp is a String) resp.equals(“yes”) resp.equalsIgnoreCase(“yes”) resp.startsWith(“y”) resp.toLowerCase()
15
Parts of a Method Call All method calls are alike: Math.pow(5, 7) kbd.nextInt(); resp.equals(“yes”) Someone.doSomething(with, these) »Someone (Math, kbd, resp, …), dot, something (pow, nextInt, equals, …), open paren, arguments (separated by commas), close paren »there may not be any arguments, but the parentheses must still be there!
16
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) resp.startsWith(7) makes no sense! »the argument must be a String: resp.startsWith(“7”) And in the right order and there must be the right number of them! »Math.pow(5) and Math.pow(1, 2, 3) make no sense!
17
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() str.regionMatches(true, 0, “this”, 7, 50)
18
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
19
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”));
20
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 a program main method has instructions in it »so will the other methods we make our (first) methods will return a value »like Math.pow, str.toUppercase, kbd.nextInt,... »(main doesn’t return a value)
21
Why Do We Make Methods? Code Re-use Doing “same” thing in multiple places » we do a lot of printing! Code Hiding (Encapsulation) Secret Implementation independence Code Abstraction Top-down design
22
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
23
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
24
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 the int that kbd.nextInt sent back to you Recall: Something a method sends back to you (like this int) is called a return value
25
Classes for Methods Scanners know how to do input lots of input methods System.out knows how to print stuff several output methods Strings know how to do things, too plus they keep track of some information (the letters in the string)
26
Creating Our Own Methods We will write our algorithms into methods we will create a class to hold the methods we put that class somewhere we can find it »(in the same project!) we will ask that class to run that algorithm Our class keeps related methods together can also keep related constants for us
27
Example Class: Converter A class for objects that know how to convert between metric and imperial/US measurements use it like this: double degF = Converter.fahrenheitFromCelsius(29.0); System.out.println(“29C = ” + degF + “F”); double hgtInCM = Converter.cmFromFeetInches(5, 8); System.out.println(“5’ 8\” = ” + hgtInCM + “cm”);
28
Compare Method Calls Converter method fahrenheitFromCelsius double degF = Converter.fahrenheitFromCelsius(29.0); takes a double value... ... and returns a double value it’s like Math.sqrt double squareRootOf10 = Math.sqrt(10); »yes, I know that 10 is an int »but the computer is expecting a double, so it changes the 10 into 10.0 automatically
29
Compare Method Calls Converter method cmFromFeetInches double hgtInCM = Converter.cmFromFeetInches(5, 8); takes two int values... ...and returns a double value kind of like Math.pow double threeToTheSeventhPower = Math.pow(3, 7); »yeah, Math.pow is expecting doubles, too! »in fact, why shouldn’t cmFromFeetInches expect inches to be a double? »Converter.cmFromFeetInches(5, 7.5) makes sense!
30
Method Purpose Method has a job to do 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)
31
In Your Project Put files together in one project NetBeans will keep them in the same folder One of the files is for your “main class” the class that has the main function in it »remember NetBeans asking you about that? Other file is for the non-main class the class that doesn’t have a main function in it »I will sometimes call this a “helper class” in our example, it’s the Converter class
32
Note on the Slides All of our classes have been programs so far now we start to write non-program classes In order to use them, we need a program… program asks non-program to do things …so we need two (or more) files program class code will be in yellow non-program class code will be in green
33
Declaring Methods Need to declare the class (just like before) public class Converter {... // methods in here //... // methods in here //} Need to declare the methods (like before) public static...... (...) {.... // commands in here //.... // commands in here //} Compare: public static void main(String[] args) {... }
34
Method Header First line of method says: public static (for now!) return type of method »int, double, String, boolean,... name of method »fahrenheitFromCelsius, cmFromFeetInches,... its parameters (variables for its arguments) »(double degC), (int ft, double in),... »what kind of value is it & what shall we call it? »in parentheses, separated by commas
35
Arguments and Parameters Arguments are values (10, 15.4, “Hello”) Parameters are variables need to be declared like variables »(double degC), (int ft, double in) only differences are: »declarations are separated by commas, not ;s »every parameter needs its own type, even if they’re all the same type: (double x, double y, double z), (int a, int b)(double x, double y, double z), (int a, int b)
36
Arguments and Parameters Parameters get their values from arguments Converter.fahrenheitFromCelsius(29.0) fahrenheitFromCelsius(double degC) »degC is set equal to 29.0 Converter.cmFromFeetInches(5, 8) cmFromFeetInches(int ft, double in) »ft is set to 5, in is set to 8.0 Converter.cmFromFeetInches(7, 1.5) cmFromFeetInches(int ft, double in) »ft is set to 7, in is set to 1.5 returns how many cm 5’ 8” is (172.72) returns how many cm 7’ 1.5” is (217.17) Every time you call a function, its parameters get new values.
37
Converter Class Beginning Here’s what we have so far: public class Converter { public static double fahrenheitFromCelsius(double degC) { public static double fahrenheitFromCelsius(double degC) { } public static double cmFromFeetInches(int ft, double in) { public static double cmFromFeetInches(int ft, double in) { }} this code won’t compile »error at end of method: missing return statement
38
The return Command Tells method what value to send back the value the method returns! return 3.5;// returns a double value // return 7; // returns an int value // return “Hello!”; // returns a String value // or, more likely, return result; where result has the value we calculated »e.g. the number of Fahrenheit degrees
39
Function “Stubs” Our methods need return commands need to return the right kind of thing we want to return exactly the right value but Java doesn’t care! So we can just put a “dummy” return in return something so that Java doesn’t complain worry about making it right later we call such a function a “stub” (it’s short)
40
Converter Class with Stubs Here’s what we have so far: public class Converter { public static double fahrenheitFromCelsius(double degC) { public static double fahrenheitFromCelsius(double degC) { return 0.0; return 0.0; } public static double cmFromFeetInches(int ft, double in) { public static double cmFromFeetInches(int ft, double in) { double result = 0.0; double result = 0.0; return result; return result; }} either way of writing the stub is fine!
41
Position of the return Command The return command is at the end when function returns a value, its job is done »it will not do anything after that so no code comes after a return command »error message: unreachable statement »another error message: missing return command next thing after a return command must be a } »nothing else makes sense!
42
The Method Body The method body is where you tell the computer how to compute the value needed »how to convert feet and inches to cm »how to convert Celsius to Fahrenheit »... Need to know how to do it... »feet times 12 plus inches, all multiplied by 2.54 ...and translate it into Java: result = (ft * 12 + in) * 2.54;
43
cmFromFeetInches Body public double cmFromFeetInches(int ft, double in) { double result = 0.0; result = (12 * ft + in) * 2.54; return result; } public static final int IN_PER_FT = 12; public static final double CM_PER_IN = 2.54; We should make CONSTANTS for the numbers we’re using here… Rewrite cmFromFeetInches to use these newly declared constants...
44
cmFromFeetInches Body double cm = Converter.cmFromFeetInches(5, 7.5); public double cmFromFeetInches(int ft, double in) { double result = 0.0; result = (IN_PER_FT * ft + in) * CM_PER_IN; return result; } 5 ft 7.5 in 0.0 result ? cm 171.45 result 171.45 cm After the value has been returned, the local variables cease to exist!
45
Local Variables The parameters and any variables you create inside the method body are “local” it only makes sense to use them in the method cannot be used outside the method »in particular, not in main! They are, in fact, temporary variables they only exist while the method is running »not before; not after. »created anew every time the method is called
46
Exercise Write the body of fahrenheitFromCelsius take degrees in Celsius multiply by 9.0/5.0 add 32.0 return the result Create constants; rewrite body to use them DEG_F_PER_DEG_C = 9.0 / 5.0 ZERO_C_IN_F = 32.0
47
fahrenheitFromCelsius Body public double fahrenheitFromCelsius(double degC) { double fahrenheitDegrees, fahrenheitTemp; fahrenheitDegrees = degC * 9.0 / 5.0; fahrenheitTemp = fahrenheitDegrees + 32.0; return fahrenheitTemp; } This body has four lines declarations & assignment statements return command at the end, as usual
48
Method Body Anything you can do in main … …you can do in a method (local) variable declarations (including objects) assignment statements selection controls (if, if-else, if-else-if) repetition controls (while, for) method calls (other things we haven’t learned about yet)
49
Exercises Write Converter methods use the constants we defined before celsiusFromFahrenheit subtract 32, then divide by 9.0 / 5.0 68 – 32 = 36; 36 / (9.0 / 5.0) = 180.0 / 9.0 = 20.0 68 F = 20 C inchesFromCM divide by 2.54 100 / 2.54 = 39.37 100cm = 39.37”
50
Input & Output Value-returning methods usually do NONE common mistake is to have it ask for the value to use – but we already gave it that value fahrenheitFromCelsius(29.0) common mistake is to have it print the answer – but what if main doesn’t want it printed? tempInCelsius = fahrenheitFromCelsius(29.0); just do the math; leave caller to do the I/O
51
Badly Behaved Function WRONG! WRONG! WRONG! WRONG! public static double fahrenheitFromCelsius(double degC) { Scanner kbd = new Scanner(System.in); System.out.print(“Enter degrees Celsius: ”); degC = kbd.nextInt(); kbd.nextLine(); double result = degC * 9.0 / 5.0 + 32.0; System.out.println(degC+ “C == ” + result + “F”); return result; } DON’T DO THIS!!!
52
Bad Behaviour // this version of the Converter is buggy double tempF = Converter.fahrenheitFromCelsius(0.0); System.out.println(“0.0C is ” + tempF + “F”); What went wrong? fahrenheitFromCelsius did I/O »user typed in 50 function returned 50 C in F instead of 0 C Enter degrees Celsius: 50 50.0C == 112.0F 0.0C is 112.0F
53
Recall Method calls all alike: Someone.doSomething(with, these) Someone is usually an object a Scanner, a String, System.out (a PrintWriter) but can be a class (Math) doSomething is the name of the method with and these are arguments to the method
54
Recall Method definition is like this: public static returnType name(pType1 p1, pType2 p2) { body... body... return result; return result;} returnType is int, or double, or String, or... »so are pType1 and pType2 name is the name of the method »p1 and p2 are the names of the parameters body is for the commands calculating the result
55
Questions
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.