7.3. Worked Example: Writing MethodsΒΆ
Subgoals for Writing Methods
Define method header based on problem
Define return statement at the end
Define method body/logic
Determine types of logic (expression, selection, loop, etc)
Define internal variables
Write statements
Problem: Write a public method that does not return anything but accepts as parameters 2 Strings and prints out a cheerful sentence with the input in it.
SG1: Define method header based on problem
public void cheerful (String a, String b)
SG2: Define return statement at the end
the return;
statement is optional for void return type.
public void cheerful (String a, String b)
{
return;
}
SG3: Define method body/logic
Determine types of logic (expression, selection, loop, etc.)
Define internal variables
Write statements
The instructions require us to concatenate a String expression for printing. One variable to store the message could be useful.
public void cheerful (String a, String b)
{
String message = a + " is happy clap your hands, " + b;
System.out.println(messsage);
return;
}
Practice Pages