Methods Part 2 (Methods Math String Class Part B) (PDF)
Document Details
Uploaded by SatisfiedDandelion6498
Tags
Summary
This document details a presentation on methods in programming. It covers different types of methods, the concept of "void" methods, and an introductory example using the Hokey Pokey song as a metaphor.
Full Transcript
Methods Part 2 Methods How to perform a method – Send a message to an object or class Building a method in Alice – Click the create new method button – Drag statements into the method You have been creating main methods, and might have created other methods al...
Methods Part 2 Methods How to perform a method – Send a message to an object or class Building a method in Alice – Click the create new method button – Drag statements into the method You have been creating main methods, and might have created other methods also in the last homework 2 Introductory Example: The Hokey Pokey Song Problem: write a Java program to display song lyrics Brute force approach – One String object stores the song lyrics – One action displays those lyrics – Implement program using one println()message – Issue: program is about 60 lines long (excessive) A better approach takes advantage of song structure – Each verse only differs by the body part that is moved – Implement program with a single method to print verse – printVerse()takes one argument for the bodyPart 3 Introductory Example: The Hokey Pokey Song (continued) 4 Introductory Example: The Hokey Pokey Song (continued) 5 Introductory Example: The Hokey Pokey Song (continued) 6 Methods (continued) Analyzing the first line of printVerse() – public: allows another class access to the method – static: indicates that the message is a class method – void: indicates that the method does not return a value – printVerse: the method’s name – (): contains parameters, such as String bodyPart – {: indicates the beginning of the method statements Simplified pattern for a Java method [AccessMode] [static] ReturnType MethodName (Params) {Statements} Alice in Action with Java 7 Non-void vs. void Methods Alice messages – Methods: just runs statements – Functions: returns a value Java - both are called methods void method in Java – Corresponds to an Alice method – Example: printVerse() non-void method in Java – Corresponds to an Alice function – Must have a return type Alice in Action with Java 8 Einstein’s Formula e = m x c2: energy = mass x speed of light2 – The formula itself serves as the user story – Method returns an expression for right side of formula Developing the massToEnergy()method – Method’s return type is a double – Parameter list includes a double type called mass – Speed of light is declared as a constant outside method – Computation is performed within return statement Example of a call to massToEnergy() – double energy = massToEnergy(1.0); 9 Einstein’s Formula (continued) 10