7.3. 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


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

  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.

public void cheerful (String a, String b)
{
   String message = a + " is happy clap your hands, " + b;
   System.out.println(messsage);
   return;
}

Practice Pages

You have attempted of activities on this page