Presentation is loading. Please wait.

Presentation is loading. Please wait.

Methods II Material from Chapters 5 & 6. Note on the Slides  We have started to learn how to write non- program Java files  classes with functions/methods,

Similar presentations


Presentation on theme: "Methods II Material from Chapters 5 & 6. Note on the Slides  We have started to learn how to write non- program Java files  classes with functions/methods,"— Presentation transcript:

1 Methods II Material from Chapters 5 & 6

2 Note on the Slides  We have started to learn how to write non- program Java files  classes with functions/methods, but no main  In order to use them, we need a program…  program tells non-program what to do  …so we need two (or more) files  code for program file will be in yellow  code for non-program file(s) will be in green

3 Last Time  Methods that return values  method call: returnType var = Class.name(arg);  method definition: public class Class { public static returnType name(pType param) { // body goes here (if needed) // body goes here (if needed) return result; return result; }} »need to fill in return type, parameters, body & result »there may be more parameters, or none

4 This Time  Methods that do not return a value  “procedures”  AKA: “void methods”, “void functions” »I don’t like “void functions”, but some people do  Used differently than function methods  void method call: Class.name(arg);  there’s no return value, and so nothing to “use” »may be no arguments, or several

5 Two Kinds of Methods  Some methods return a value to you  nextInt returns an int  fahrenheitFromCelsius returns a double  equalsIgnoreCase returns a boolean  These called value-returning methods  Other methods do not return values  print and println, for example  Those are called void methods

6 Value-Returning Function Calls word = keyboard.next(); while (!word.equals(“.”))  Value-returning functions used in expressions  often in assignment statements  also in logical expressions Method ArgumentsMethod Name Object

7 Void Function Calls System.out.print(“Enter a #”); System.out.print(“\n\n”);  Void functions used as complete statements  not in any expression  have no value (“void” = empty/nothing) Method ArgumentsMethod Name Object

8 Return or No Return?  Void methods do things; don’t return things  println prints a String  the String gets printed  the String does not get returned String s = System.out.println(“Hello?”);  nothing gets returned! int n = System.out.println(“10”); incompatible types: void cannot be converted to String incompatible types: void cannot be converted to int

9 Exercise  Void or value-returning?  & what kind of value does each VRM return? if (answer.startsWith(“Y”)) { double x = Math.pow(3, 6); double x = Math.pow(3, 6); int n = kbd.nextInt(); int n = kbd.nextInt(); System.out.println(“Hello!”); System.out.println(“Hello!”); myWin.setVisible(true); myWin.setVisible(true); double cm = Converter.cmFromFeetInches(n, x); double cm = Converter.cmFromFeetInches(n, x); thingamajig.doStuff(cm, x, that.get(n)); thingamajig.doStuff(cm, x, that.get(n));} Note: there are two method calls on the last line. How can we find out what kind of value get returns?

10 void Method Definition  Very similar to function method definition  put “void” for the return type »“void” means “nothing”: the method returns nothing  don’t use a return command »there’s nothing to return! public class Class { public static void name(pType param) { // body goes here // body goes here }}

11 What’s it for?  It’s to do things  for example, to print something: System.out.println(“Hello, World!”);  System.out is the object (it’s a PrintWriter) »System is a class, and out belongs to System  println is the name of the method  println expects to be given a String »(or some other thing, or nothing; it’s complicated)

12 Example  Write a method that prints out the self- identification for A07:  Including the blank lines before and after  Call like this: Utilities.printA07Identification(); A00000000 -- Young, Mark CSCI 1226 -- Fall 2015 A07 -- due 2015-11-20 What is the method’s name? What class is it defined in? How can we tell it’s a void method?

13 Naming Methods  Method names in mixed case  capital letter for 2 nd and subsequent words  Value-returning methods have noun-like names  say what the value is: fahrenheitFromCelsius  void functions have command-like names  tell program what to do: printA07Identification

14 Exercise  Create names for the following methods  gives us the factorial value of a number »(e.g. 5! = 5 * 4 * 3 * 2 * 1 = 120)  figures out how many students failed a test a)... and returns that value to us b)... and prints a message telling us the number  draws a snowman in a (given) window

15 printA07Identification  Start with just a stub  a small definition that compiles public class Utilities { public static void printA07Identification() { public static void printA07Identification() { }}  Note: void methods have no return command »so void method stub can actually be empty  maybe S.o.pln(“Print A07 identification here”);

16 printA07Identification  Add code to do what needs doing  one command, or many public static void printA07Identification() { System.out.println(); System.out.println(); System.out.println(“A00000000 -- Young, Mark”); System.out.println(“A00000000 -- Young, Mark”); System.out.println(“CSCI 1226 -- Fall 2015”); System.out.println(“CSCI 1226 -- Fall 2015”); System.out.println(“A07 -- due 2015-11-20”); System.out.println(“A07 -- due 2015-11-20”); System.out.println(); System.out.println();}

17 Commenting Methods  Methods should have javadoc comments  start with /**, end with */  at least a brief description of the method: /** Prints the identification information for A07. */ /** Converts distance in feet and inches to cm. */  hover over method header in Navigator pane… »lower left side of NetBeans window  …to see your comment

18 Commenting Methods  Better (but NOT REQUIRED):  add @param for each parameter (if any)  add @return if it’s a value-returning method /** * Converts distance from feet and inches to centimetres. * Converts distance from feet and inches to centimetres. * * @param ft (whole) number of feet in the distance * @param ft (whole) number of feet in the distance * @param in number of (extra) inches in the distance * @param in number of (extra) inches in the distance * @return same distance, but measured in centimetres * @return same distance, but measured in centimetres */ */

19 Commenting Methods  A longer description may be appropriate.  add HTML markup to format the comment /** * Prints the identification information for A07. * Prints the identification information for A07. * * * The identification consists of the author’s A-number and name, * The identification consists of the author’s A-number and name, * the course title and term, and the assignment number and due date. * the course title and term, and the assignment number and due date. * These are printed on three lines, with double hyphens between the * These are printed on three lines, with double hyphens between the * two items on each line. * two items on each line. */ */ is HTML for “start a new paragraph.” You DO NOT need to learn HTML for this course!

20 Arguments to a Method  Some methods need more information  what is it you want me to print?  what distance do you want me to convert?  In parentheses after the method name System.out.println(“OK!”); cm = Converter.cmFromFeetInches(3, 5);  Still need parentheses even if no arguments num = kbd.nextInt(); Utilities.printA07Identification();

21 Arguments and Parameters  Method definition needs one parameter for each argument  parameter is a variable to hold the argument  Parameter must be the right data type  argument is double  parameter is double  argument is String  parameter is String  argument is boolean  parameter is boolean  argument is int  parameter is int (or double) »computer will change int to double when it needs to

22 Method Parameters public static double fahrenheitFromCelsius(double degC) { …}  double degC  needs to be given a double value (int is OK) »it will be given a value! »not giving it a value is a mistake (syntax error)  it will call the value it’s been given degC »it might be 10.0, 37.5, -40.0, 10000000.0, … »whatever it is, it’s saved in degC

23 Method Parameters public static double cmFromFeetInches(int ft, double in) { …}  This method has two parameters  it’s expecting to be given two things  the first thing will be an int (we’ll call it ft)  the second thing will be a double (in) Arguments & parameters match up in order – first argument  first parameter, second argument  second parameter, …

24 Parameters are Local  The method’s parameter(s) can only be used in that method  just like a for loop’s loop control variable  You can give it any (valid) name you want  doesn’t matter who else uses that name »or if no one else uses that name  should say what it holds, tho »ft holds # of feet, degC holds a temp. in Celsius.

25 Local Variables for (int c = 0; c < 10; ++c) { Converter.fahrenheitFromCelsius(c); Converter.fahrenheitFromCelsius(c); Sopln(degC + “C is ” + degF + “F”); Sopln(degC + “C is ” + degF + “F”);} public static double fahrenheitFromCelsius(double degC) { double degF = 32.0 + 9.0 * degC / 5.0; double degF = 32.0 + 9.0 * degC / 5.0; return degF; return degF;} Symbol not found: degC Symbol not found: degF Assign return value to new variable

26 Hacking for (int c = 0; c < 10; ++c) { double degC, degF; double degC, degF; Converter.fahrenheitFromCelsius(c); Converter.fahrenheitFromCelsius(c); Sopln(degC + “C is ” + degF + “F”); Sopln(degC + “C is ” + degF + “F”);} public static double fahrenheitFromCelsius(double degC) { double degF = 32.0 + 9.0 * degC / 5.0; double degF = 32.0 + 9.0 * degC / 5.0; return degF; return degF;} degC not initialized degF not initialized Assign return value to new variable

27 Hacking for (int c = 0; c < 10; ++c) { double degC = 0.0, degF = 0.0; double degC = 0.0, degF = 0.0; Converter.fahrenheitFromCelsius(c); Converter.fahrenheitFromCelsius(c); Sopln(degC + “C is ” + degF + “F”); Sopln(degC + “C is ” + degF + “F”);} public static double fahrenheitFromCelsius(double degC) { double degF = 32.0 + 9.0 * degC / 5.0; double degF = 32.0 + 9.0 * degC / 5.0; return degF; return degF;} Assign return value to new variable 0.0C is 0.0F

28 Hacking for (int c = 0; c < 10; ++c) { double degC = 0.0, degF = 0.0; double degC = 0.0, degF = 0.0; degF = Converter.fahrenheitFromCelsius(c); degF = Converter.fahrenheitFromCelsius(c); Sopln(degC + “C is ” + degF + “F”); Sopln(degC + “C is ” + degF + “F”);} public static double fahrenheitFromCelsius(double degC) { double degF = 32.0 + 9.0 * degC / 5.0; double degF = 32.0 + 9.0 * degC / 5.0; return degF; return degF;} 0.0C is 32.0F 0.0C is 33.8F 0.0C is 35.6F 0.0C is 37.4F 0.0C is 39.2F

29 Local Variables for (int c = 0; c < 10; ++c) { double f = Converter.fahrenheitFromCelsius(c); double f = Converter.fahrenheitFromCelsius(c); Sopln(c + “C is ” + f + “F”); Sopln(c + “C is ” + f + “F”);} public static double fahrenheitFromCelsius(double degC) { double degF = 32.0 + 9.0 * degC / 5.0; double degF = 32.0 + 9.0 * degC / 5.0; return degF; return degF;} 0C is 32.0F 1C is 33.8F 2C is 35.6F 3C is 37.4F 4C is 39.2F

30 Arguments  Remember that arguments are extra information we give to a method  information it needs to do its job  Each time you call the method, the arguments are “passed to” the method, and it uses them  System.out.println(“Hello!”); prints “Hello!”  System.out.println(“Bye!”); prints “Bye!

31 Arguments to User Methods  User methods are the same! Utilities.printAssignmentInformation(7, “2015-11-20”); Utilities.printAssignmentInformation(8, “2015-11-27”); A00000000 -- Young, Mark CSCI 1226 -- Fall 2014 A07 -- due 2015-11-20 A00000000 -- Young, Mark CSCI 1226 -- Fall 2014 A08 -- due 2015-11-27

32 Exercise  Write that method: Utilities.printAssignmentInformation(7, “Friday”);  What’s its name?  What class is it in?  What kinds of arguments does it take? »what are those arguments for? A00000000 -- Young, Mark CSCI 1226 -- Fall 2015 A07 -- due Friday System.out.printf(“A%02d”, 1); will print A01

33 More Utilities Methods  A class with helpful printing methods  use it like this: Utilities.printTitle(“Utilities Demo”); Utilities.printParagraph(“This program demonstrates ” + “the Utilities class.”); Utilities.printParagraph(“This paragraph was produced ” + “by the printParagraph method.”); Utilities.printParagraph(“This paragraph’s much longer ” + “than the one above, and needs to be \“wrapped\” ” + “on the output line. The method does that for us!”);

34 Titles and Paragraphs  printTitle  print underlined, with blank lines  printParagraph  wrap words, add blank line Utilities Demo -------------- This program demonstrates the Utilities class. This paragraph was produced by the printParagraph method. This paragraph’s much longer than the one above and needs to be “wrapped” on the output line. The method does that for us!

35 Utilities Class Stubs public class Utilities{ public static void printAssignmentIdentification (int a, String d) { public static void printAssignmentIdentification (int a, String d) { } public static void printTitle(String title) { } public static void printParagraph(String text) { }}

36 printTitle Body public void printTitle(String title) { System.out.print("\n" + title + "\n"); System.out.print("\n" + title + "\n"); for (int i = 1; i <= title.length(); i++) for (int i = 1; i <= title.length(); i++) System.out.print('-'); System.out.print('-'); System.out.print("\n\n"); System.out.print("\n\n");}  print blank line and title; end title line  for each letter in the title »print a hyphen (to underline that letter)  end underline line, print blank line

37 printParagraph Body  printParagraph is more complicated  needs to break the String into words  needs to print each word, BUT…  … before it prints a word, it needs to know if there’s enuf space for it »if not, we need to end the line before we print it »so needs to keep track of how much space is used  but it’s just a programming problem »same as if we’d asked for a program to do it

38 Fitting Words on Lines  Check for space first; maybe go to new line  Print word after that printParagraph(“These are the words to print on the screen, ” + “which is only 20 spaces wide.”); 01234567890123456789 Thesearethewordsto printonthescreen,to screen,whichisonly 20spaceswide.

39 Fitting Words on a Line  Track how many spaces used so far int spacesUsedSoFar = 0;  Check word’s length (plus one for the space after!) int spacesNeeded = word.length() + 1;  If there’s not enuf space, go to the next line if (spacesUsedSoFar + spacesNeeded > MAX_LINE_LENGTH) { System.out.println(); spacesUsedSoFar = 0; System.out.println(); spacesUsedSoFar = 0;}  Print the word; update the number of spaces used System.out.print(word);spacesUsedSoFar += spacesNeeded;

40 Breaking a String into Words  We know how to get words from the user Scanner kbd = new Scanner(System.in); String userWord = kbd.next();  System.in is (essentially) the keyboard  kbd reads from the keyboard (hence its name)  Only need to change System.in to the String Scanner str = new Scanner(“One two three”); String stringWord = str.next();// stringWord == “One”  str reads from the String!

41 The Scanner in printParagraph  The String to print is given to the method  the method creates the Scanner on the String public static void printParagraph(String text) { Scanner para = new Scanner(text); Scanner para = new Scanner(text); while (para.hasNext()) { while (para.hasNext()) { String word = para.next(); String word = para.next();  the hasNext() method checks whether there are any more words in the String ».: the loop runs until there are no more words left

42 Objects  A Scanner is an object  it has its own data as well as its own methods  kbd knows it must read from the keyboard  str knows it must read from a String  How? We told it when we made it! kbd = new Scanner(System.in); str = new Scanner(text);  each object remembers its own data  that’s useful!

43 Next Time  How do we write classes for objects?


Download ppt "Methods II Material from Chapters 5 & 6. Note on the Slides  We have started to learn how to write non- program Java files  classes with functions/methods,"

Similar presentations


Ads by Google