Algorithms: 8 Algorithm: A List of Steps For Solving A Problem. 8 Example Algorithm: "Bake Cookies"
Algorithms: 8 Algorithm: A List of Steps For Solving A Problem. 8 Example Algorithm: "Bake Cookies"
method C
8 Writing a method is like statement
statement
adding a new command to Java. statement
5
Using methods
1. Design the algorithm.
– Look at the structure, and which commands are repeated.
– Decide what are the important overall tasks.
– Good programmers do this BEFORE writing any code
8 Example:
public void printWarning()
8 {
System.out.println("This product causes cancer");
System.out.println("in lab rats and humans."); 7
Calling a method
Executes the method's code
8 Syntax:
<name>();
– You can call the same method many times if you like.
8 Example:
printWarning();
– Output:
This product causes cancer
in lab rats and humans.
8
Program with static method
public class FreshPrince
{
public static void main(String[] args)
{
rap(); // Calling (running) the rap method
System.out.println();
rap(); // Calling the rap method again
}
Output:
Now this is the story all about how
My life got flipped turned upside-down
8 Output:
This is message1.
This is message2.
This is message1.
Done with message2.
Done with main.
11
Control flow
8 When a method is called, the program's
execution...
– "jumps" into that method, executing its statements, then
– "jumps" back to the point where the method was called.
13
8 How many lines of output does the following program produce?
A. 3 B. 4
C. 8 D. 12
E. 20
8 ANSWER
A. 3 B. 4 C. 8 D. 12 E. 20