Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
Lecture 10 SYS-1S22 / MTH-1A66 Methods Stuart Gibson [email protected] S01.09A 1 DecimalFormat Again • DecimalFormat rounds the input when formatting to a set number of decimal places. import java.text.*; Specify Two Decimal Places public class DFTest { public static void main (String[] args) { DecimalFormat fmt = new DecimalFormat(“0.00”); double x = 3.215, y = 3.2149; System.out.println(“x: ” + fmt.format(x)); System.out.println(“y: ” + fmt.format(y)); } } x: 3.22 y: 3.21 2 1 Data Types : Strings • So far we have only been using primitive data types: int, double, char, boolean. • Another popular data type are Strings. (note the capital S!) • Strings are objects that are included in the Java Library. • So far we have seen and used String literals e.g: System.out.println(“Hello World”); String literal 3 Data Types : Strings • Even though they are not primitive types, Strings are so fundamental and so often used that Java defines String literals delimited by double quotation marks as we have seen. • This is a shortcut notation, whenever a String literal appears a String object is created. • With this shortcut notation we can declare and assign Strings just as we did with chars e.g. char singleChar = ‘H’; String manyChar = “Hello”; • For String assignment we use double quotes “ 4 2 Data Types : Strings • A String is an array of characters: H e l l o • We can declare String variables and read them in from the keyboard. String input; input = Keyboard.readString(); • So it seems that we can use Strings just as we do all other primitives. However if we use the same operators for comparison, we can get some strange results: 5 Data Types : Strings public class StringTest { public static void main (String[] args) { String name = "Stuart"; String input; System.out.println("Enter your name: "); input = Keyboard.readString(); if(input == name) { System.out.println("Your name is "+name); } else { System.out.println("Your name is NOT "+name); } } } Are we feeling brave: Live demo! 6 3 Data Types : Strings • Even if the String entered is the same, the answer when compared using the == evaluates to false and so we print out that they are not the same. • This behaviour is because Strings are objects and not primitives, so to compare objects we have to do something different, more next week. • So for now we shall just use them for simple tasks such as printing them out. String name = “Fred”; System.out.println(“Hello ”+ name); 7 So Far…. • We can repeat statements, num times using a for loop for (int i=1; i <= num; i++) { System.out.println(i +“. Hello ”+name); } 1. Hello Stuart 2. Hello Stuart 3. Hello Stuart 4. Hello Stuart What if more than one variable changes ? What about using this for loop again later in the program ? 8 4 Code Repetition • So far the only way would be to re-type the for loop. for (int i=1; i <= num; i++) { System.out.println(i +“. Hello ”+name); } System.out.println(“After all this……”); System.out.print(“I would like Hello “+name); System.out.print(“ on lines 1 to ”+num+“ again!”); for (int i=1; i <= num; i++) { System.out.println(i +“. Hello ”+name); } • Problem: Most people dislike unnecessary work. • Solution: Write code that is reusable. 9 Simple Problem Write a program that displays the lyrics of the children’s song Old Macdonald, which go as follows: Old Macdonald had a farm, E-I-E-I-O, And on this farm he had a cow, E-I-E-I-O, With a moo-moo here and a moo-moo there, Here a moo there a moo everywhere a moo-moo Old Macdonald had a farm, E-I-E-I-O. Old Macdonald had a farm, E-I-E-I-O, And on this farm he had a sheep, E-I-E-I-O, With a baa-baa here and a baa-baa there, Here a baa there a baa everywhere a baa-baa Old Macdonald had a farm, E-I-E-I-O. ………. Many more verses 10 5 Simple Implementation Initial Approach public class SimpleOldMacdonald { public static void main(String[] args) { System.out.print("Old Macdonald had a farm, E-I-E-I-O,\n" + "And on this farm he had a cow, E-I-E-I-O, \n" + "With a moo-moo here and a moo-moo there, \n" + "Here a moo there a moo everywhere a moo-moo, \n" + "Old Macdonald had a farm, E-I-E-I-O.\n\n"); System.out.print("Old Macdonald had a farm, E-I-E-I-O,\n" + "And on this farm he had a sheep, E-I-E-I-O, \n" + "With a baa-baa here and a baa-baa there, \n" + "Here a baa there a moo everywhere a baa-baa, \n" + "Old Macdonald had a farm, E-I-E-I-O.\n\n"); //Many More Verses } } 11 Problem Analysis • Out of the 40 words in a verse, 32 are repeated in every verse! • Solution: Eliminate redundant code. What is the difference between the verses? Old Macdonald had a farm, E-I-E-I-O, And on this farm he had a cow, E-I-E-I-O, With a moo-moo here and a moo-moo there, Here a moo there a moo everywhere a moo-moo Old Macdonald had a farm, E-I-E-I-O. Old Macdonald had a farm, E-I-E-I-O, And on this farm he had a sheep, E-I-E-I-O, With a baa-baa here and a baa-baa there, Here a baa there a baa everywhere a baa-baa Old Macdonald had a farm, E-I-E-I-O. 12 6 Problem Analysis • Out of the 40 words in a verse, 32 are repeated in every verse! • Solution: Eliminate redundant code. What is the difference between the verses? Old Macdonald had a farm, E-I-E-I-O, And on this farm he had a cow, E-I-E-I-O, With a moo-moo here and a moo-moo there, Here a moo there a moo everywhere a moo-moo Old Macdonald had a farm, E-I-E-I-O. Old Macdonald had a farm, E-I-E-I-O, And on this farm he had a sheep, E-I-E-I-O, With a baa-baa here and a baa-baa there, Here a baa there a baa everywhere a baa-baa Old Macdonald had a farm, E-I-E-I-O. 13 Solution Design Can we make a generic verse? Old Macdonald had a farm, E-I-E-I-O, And on this farm he had a animal, E-I-E-I-O, With a sound-sound here and a sound-sound there, Here a sound there a sound everywhere a sound-sound Old Macdonald had a farm, E-I-E-I-O. • The items that differ between the verses are known as the parameters of the verse. • We require variables to represent the parameters String animal; String sound; How do we print each verse using these variables? 14 7 Method Example public class OldMacdonald { // First Attempt at a method public static void buildVerse(String animal, String sound) { System.out.print("Old Macdonald had a farm, E-I-E-I-O,\n" + "And on this farm he had a "+animal+", E-I-E-I-O, \n" + "With a "+sound+"-"+sound+" here and a "+sound+"-"+sound + "there, \n" + "Here a "+sound+" there a "+sound+" everywhere a “ + sound+"-"+sound+", \n" + "Old Macdonald had a farm, E-I-E-I-O.\n\n"); } public static void main(String[] args) { buildVerse("cow","moo"); // Calls Method for cow buildVerse("sheep","baa"); // Calls Method for sheep } } 15 Method Declaration public static void buildVerse(String animal, String sound) { // statements to print out a verse // The part between the curly braces is the method body } • This is the method declaration. • The method name is buildVerse. We could call it almost anything we like! Although there are a few exceptions such as keywords etc. • More about public and static later… • The method concatenates the “hard-wired” Strings such as “Have a ” with the values stored in the String variables animal and sound. 16 8 Invoking the Method • In the main method we see the statement: buildVerse(“cow”,“moo”); Method Identifier (Name) Arguments • The main progam calls the buildVerse method to invoke it. • The buildVerse method takes two arguments. • The arguments are both String types. • In the example above, the main program passes the “hardwired” values of “cow” and “moo” to the buildVerse method. 17 Method Initialisation • The main program calls the buildVerse method: buildVerse(“cow”,“moo”); • The method declaration: passes buildVerse(String animal,String sound); • The method declares two parameters: animal and sound that are both String types. • When the method is called the variables animal and sound are initialised to the values passed from the main method. • In our example: animal is initialised to “cow” sound is initialised to “moo” 18 9 Method Execution Flow The main method The buildVerse method buildVerse(“cow”,“moo”); • Calls method • The two arguments are set to “cow” and “moo” and passed to the buildVerse method. animal sound “cow” “moo” • Concatenate Strings • Output to Screen • Return to main method buildVerse(“sheep”,“baa”); Flow of execution 19 Method Execution Flow • main method pauses when it invokes buildVerse method. • Control passes to buildVerse method. • buildVerse method executes • When buildVerse terminates, it returns control back to the main method • main method continues. 20 10 Method Output buildVerse(“cow”,“moo”); Old Macdonald had a farm, E-I-E-I-O, And on this farm he had a cow, E-I-E-I-O, With a moo-moo here and a moo-moo there, Here a moo there a moo everywhere a moo-moo Old Macdonald had a farm, E-I-E-I-O. buildVerse(“sheep”,“baa”); Old Macdonald had a farm, E-I-E-I-O, And on this farm he had a sheep, E-I-E-I-O, With a baa-baa here and a baa-baa there, Here a baa there a baa everywhere a baa-baa Old Macdonald had a farm, E-I-E-I-O. 21 Method Variables - Scope • The scope of a variable is from when it is declared to the closing curly brace of the part of the code in which it was declared. • The variable is created when it is declared. • The variable is destroyed after the closing brace of the block of code it was declared in. • The variables animal and sound are available in the buildVerse method only. • They are local to the buildVerse method. • They do NOT exist in the main method. 22 11 Scope Error For example the following code would give a compilation error: public static void main(String[] args) { buildVerse("cow","moo"); System.out.println(animal); } cannot resolve symbol symbol: variable animal location: class OldMacdonald System.out.println(animal) ^ 23 Passing Variables to a Method • In our previous example the values of the arguments passed to the method were “hard-wired”. • In practice we want to use variables to store the values that are passed to the method, for example: public static void main(String[] args) { String animalOne = “cow”; String animalOne_snd = “moo”; buildVerse( animalOne, animalOne_snd ); } public static void buildVerse(String animal, String sound) • Why do the variables have different names in the main method and the buildVerse method ? 24 12 Passing Variables to a Method • animalOne and animalOne_snd are local to the main method. • The variable name is NOT passed to the method. • The compiler evaluates what the value of the variable is and then passes that to the method. • In our example, the compiler evaluates: animalOne and animalOne_snd to “cow” and “moo” respectively and then sends these to the buildVerse method. • In the buildVerse method: The value of animal is set to “cow” The value of sound is set to “moo” 25 Passing Variables to a Method Argument: animalOne animalOne_snd “cow” “moo” “cow” Parameter: “moo” “cow” “moo” animal sound 26 13 Returning Variables from a Method What happens if you are asked to repeat the song lyrics? public static void main(String[] args) { // Calls Method for cow buildVerse("cow","moo"); // Calls Method for sheep buildVerse("sheep","baa"); // build remaining verses of the song // repeat song buildVerse("cow","moo"); buildVerse("sheep","baa"); // build remaining verses of the song } Is it necessary to call the buildVerse method twice (or possibly more) times per animal? 27 Returning Variables from a Method • At present buildVerse has a return type of void . public static void buildVerse(String animal, String sound) • void means that the buildVerse method does not pass anything back to the point where it was called from. • However we can return a variable back to where it was invoked, when the method terminates. 28 14 Returning Variables from a Method public static String buildVerse(String animal, String sound) { String verse = "Old Macdonald had a farm, E-I-E-I-O,\n“+ "And on this farm he had a "+ animal+", E-I-E-I-O, \n"+ // rest of verse return verse; } • The type of the variable to be returned MUST be the same as the type specified in the method declaration. 29 Returning Variables from a Method • If you specify a return type you MUST return the same type else you will get a compilation error: public static String buildVerse(String animal, String sound) { // statements return; } OldMacdonald.java:10: missing return value return; ^ 30 15 Returning Variables from a Method • If you specify a return type you MUST return the same type else you will get a compilation error: public static String buildVerse(String animal, String sound) { // statements } OldMacdonald.java:10: missing return statement { ^ 31 Returning Variables from a Method public static void main(String[] args) { String cowVerse = buildVerse("cow","moo"); String sheepVerse = buildVerse("sheep","baa"); System.out.print(cowVerse); System.out.print(sheepVerse); //to repeat System.out.print(cowVerse); System.out.print(sheepVerse); } • Here buildVerse is only executed twice, but the results can be used many times! 32 16 Returning Method – Execution Flow The main method The buildVerse method cowVerse = buildVerse(“cow”,“moo”); • Calls method • Passes two String arguments • cowVerse is set to the value that is returned from the method cowVerse animal sound “cow” “moo” • Concatenate strings and store result in verse variable. verse “Old Macdonald had a farm, E-I-E-I-O, And on that farm he had a cow, E-I-E-I-O ………………..” “Old Macdonald had a farm, E-I-E-I-O, And on that farm he had a cow, E-I-E-I-O ………………..” sheepVerse = buildVerse(“sheep”,“baa”); return verse; Flow of execution 33 Tracing the Execution - Debugging public static void main(String[] args) { System.out.println(“BEFORE CALL \n”); String cowVerse = buildVerse("cow","moo"); System.out.println(“AFTER CALL \n”); System.out.print(“cowVerse:\n” + cowVerse); } 34 17 Tracing the Execution - Debugging public static String buildVerse(String animal, String sound) { System.out.println(“In buildVerse Method!”); System.out.println(“animal: ”+animal); System.out.println(“sound: ”+sound); String verse = "Old Macdonald had a farm, E-I-E-I-O,\n“+ "And on this farm he had a "+animal+ ", E-I-E-I-O, \n"+ // rest of verse System.out.println(“End of Method”); System.out.println(“Verse:\n”+verse+”\n”); return verse; } 35 Tracing the Execution - Output BEFORE CALL In buildVerse Method! animal: cow sound: moo End of Method Verse: Old Macdonald had a farm, E-I-E-I-O, And on this farm he had a cow, E-I-E-I-O, With a moo-moo here and a moo-moo there, Here a moo there a moo everywhere a moo-moo Old Macdonald had a farm, E-I-E-I-O. AFTER CALL cowVerse: Old Macdonald had a farm, E-I-E-I-O, And on this farm he had a cow, E-I-E-I-O, With a moo-moo here and a moo-moo there, Here a moo there a moo everywhere a moo-moo Old Macdonald had a farm, E-I-E-I-O. 36 18 Formal Method Syntax modifiers returnType methodName(parameterDeclarations) { statements } modifiers Java keywords that describe the method: public, static, final, … returnType Type of value returned: double, int, String, … A method that returns nothing has a return type of void methodName Identifier that names the method: getSize, calcTime, … parameterDeclarations List of parameter declarations, separated by commas: int a, String b, statements Sequence of statements that define the behaviour of the method. 37 return statement return expression • return is a Java keyword. • The expression MUST be the same type as the method’s return type. • This statement causes the method to terminate. • Execution transfers back to the point where the method was called. A method with return type of void • nothing is returned to where the method was called from. • Method terminated by either: • single return statement e.g. return; • at the terminating curly bracket } 38 19 Method Design Create a method to raise a number by a power Example: 23 = 8 Analysis Parameters Type Base Exponent int int Return: Result Value of baseexponent as int Algorithm Design Result = base; Result = result*base; (Repeat exponent - 1 times) 39 Method Implementation public static int power (int base, int exponent) { int result = base; for (int i = 1; i< exponent; i++) { result = result*base; } return result; } 40 20 Testing the Method public static void main (String[] args) { int base = 2; int exp = 3; int result = power(base, exp); System.out.print(“Result of raising "+base); System.out.print(“ to the power “); System.out.print(exp+" is “); System.out.print(result + “\n”); } Result of raising 2 to the power 3 is 8 41 Food for thought! • Is the power method correct ? • Can we make assumptions about the parameters passed to the method ? • Can we have more than one method with the same name ? • If the variable passed to the method from the main method and the parameter declared in the method have the same name, does the variable in the main method change? 42 21