Skip to main content

Section 9.5 Worked Example: Writing Methods

Subgoals for Writing Methods.

  1. Define method header based on problem
  2. Define return statement at the end
  3. Define method body/logic
    1. Determine types of logic (expression, selection, loop, etc.)
    2. Define internal variables
    3. Write statements

Subsection 9.5.1

Problem: Write a public method that does not return anything but accepts as parameters 2 Strings and prints out the first parameter concatenated with any string content followed by the second parameter.

Subsection 9.5.2 SG1: Define method header based on problem

public void cheerful (String a, String b)

Subsection 9.5.3 SG2: Define return statement at the end

the return; statement is optional for void return type.
public void cheerful (String a, String b)
{
   return;
}

Subsection 9.5.4 SG3: Define method body/logic

  1. Determine types of logic (expression, selection, loop, etc.)
  2. Define internal variables
  3. Write statements
The instructions require us to concatenate a String expression for printing. One variable to store the message could be useful.
Answer.
public void cheerful (String a, String b)
{
   String message = a + " is happy clap your hands, " + b;
   System.out.println(messsage);
   return;
}

Subsection 9.5.5 Practice Pages

You have attempted of activities on this page.