User Defined Methods Review Questions and Exercises

From CompSciWiki
Revision as of 15:41, 20 March 2007 by Umhawwv (Talk | contribs)

Jump to: navigation, search

COMP 1010 Home > Back to Chapter Topics


Introduction

To familiarize yourself with creating user-defined methods, this page contains review questions and exercises. All the answers to the questions can be found on the chapter pages, and sample solutions are provided for each exercise.

   

{{{Body}}}

Review Questions

Question 1.

Explain the relationship between an argument and its corresponding parameter. Do not define argument or parameter.


Answer: During a method call, the calling method passes one argument to each parameter of the called method.


Question 2.

Which of the following methods completes execution first? What does this tell you about the order in which nested methods are executed?

System.out.println( JOptionPane.showInputDialog("Please enter a message:") );


Answer: JOptionPane.showInputDialog executes first, then passes its return value as an argument to System.out.println. When method calls are nested, the inner-most methods are executed first, because the outer methods need the inner methods' return values.

Question 3.

What are the valid names that a method name can have?


Answer: Any valid identifier name for variables may also be used as a method name.

Question 4.

How many parameters can a method have?


Answer: You can have as many parameters defined as you want. However, if there are too many, you should consider splitting it up into multiple methods.


Question 5.

What is a local variable, and how does it relate to method scope?


Answer: A local variable is a variable that is defined within a method. Method scope is the section of code where the local variable is visible.

Exercises

Exercise 1.

Write a user-defined method which has an int parameter called numReps and returns a String. The String will contain a sequence.

  • If numReps is odd, the sequence is "+*".
  • If numReps is even, the sequence is "/_".

The parameter numReps determines how many times the sequence is repeated in the String. For example:

  • When numReps is 2, the pattern is "/_/_".
  • When numReps is 5, the pattern is "+*+*+*+*+*".

When you are finished, write a main method which tests your new user-defined method. Try the inputs 3, 4, and 0.


Solution:

public class PatternSequence
{
   /**
    * This method creates a String consisting of a repeated series of characters.
    *
    * @param numReps - The number of times to repeat the sequence.
    *
    * @return String result - The built String.
    */
    public static String buildSequence(int numReps)
    {
        final String ODD_PATTERN = "+*";
        final String EVEN_PATTERN = "/_";

        String pattern; // Either "+*" or "/_"
        String result = ""; // The String to return

        // If numReps is even, the pattern is "/_"
        if(numReps % 2 == 0)
        {
            pattern = EVEN_PATTERN;
        }

        // If numReps is odd, the pattern is "+*"
        else
        {
            pattern = ODD_PATTERN;
        }

        // numReps determines how many times the pattern is repeated
        for(int i=0; i<numReps; i++)
        {
            result += pattern;
        }

        return result;
    }

    // Main method
    public static void main(String[] args)
    {
        // Let's test this out!
        System.out.println(buildSequence(3));
        System.out.println(buildSequence(4));
        System.out.println(buildSequence(0));

    }
}

Exercise 2.

Write a user-defined method which calculates the area of a triangle, called getTriangleArea. The formula is:

       base x height
area = _____________

            2

All values are of the double type.

Next, write a method called printArea which accepts a base parameter and a height parameter. The method prints the base, height, and area. Within this method you will call getTriangleArea.

Finally, write a main method which tests printArea. Try the following inputs: base = 2, height = 4; base = 5, height = 3; base = 0, height = 17.


Solution:

public class TriangleArea
{
   /**
    * This method calculates the area of a triangle.
    *
    * @param base - The size of the triangle base.
    * @param height - The height of the triangle.
    *
    * @return double result - The area of the triangle.
    */
    public static double getTriangleArea(double base, double height)
    {
        double result = (base * height) / 2;

        return result;
    }

   /**
    * This method prints the base, height, and area of a triangle.
    *
    * @param base - The size of the triangle base.
    * @param height - The height of the triangle.
    *
    * @return void
    */
    public static void printArea(double base, double height)
    {
        double area = getTriangleArea(base, height);

        System.out.println("Base:   " + base);
        System.out.println("Height: " + height);
        System.out.println("Area:   " + area);
        System.out.println();
    }

    // Main method
    public static void main(String[] args)
    {
        // Let's test this out!
        printArea(2, 4);
        printArea(5, 3);
        printArea(0, 17);
    }
}


Exercise 3.

Identify and correct the problems found in this method:

public static void FindBiggest( num1, num2, num3 )
    if (( num1 > num2 ) && ( num1 > num3 ))
    {
        return num1;
    }
    else if (( num2 > num1 ) && ( num2 > num3 ))
    {
        return num2;
    }
    else
    {
        return num3;
    }


Solution:

public static int findBiggest( int num1, int num2, int num3 )
{
    int biggest;

    if (( num1 > num2 ) && ( num1 > num3 ))
    {
        biggest = num1;
    }
    else if (( num2 > num1 ) && ( num2 > num3 ))
    {
        biggest = num2;
    }
    else
    {
        biggest = num3;
    }

    return biggest;
}


Exercise 4.

Write a method called processNumbers which does the following:

  1. Takes two doubles, dbl1 and dbl2, as its parameters.
  2. Calculate the sum of the two doubles, and store it in a variable called sum.
  3. Calls the Math.sqrt function to get the square root of the sum, and return it.


Solution:

public static double processNumbers( double dbl1, double dbl2 )
{
    double sum;            //This will store the sum of the two doubles
    double squareRoot;     //This will store the square root of sum

    sum = dbl1 + dbl2;     //Calculate the sum

    squareRoot = Math.sqrt( sum );    //Call the Math.sqrt method to calculate square root

    return squareRoot;
}


Exercise 5.

A palindrome is a string that reads the same, forwards and backwards. Examples of palindromes:

  1. STAR RATS
  2. WAS IT A RAT I SAW
  3. I PREFER PI
  4. STAR COMEDY BY DEMOCRATS

Write a method called isPalindrome which does the following:

  1. Takes a string as it's only parameter
  2. Uses a loop to check is the letters are the same at each ends
  3. uses the charAt() function to compare chars.


Solution:

public static boolean isPalindrome ( String myString )
{
    int i,j; //these will be used as letter count holders
    int myLength; // the length of myString
    
    myLength= myString.length();

    j = myLength -1;     

    // start at the begining and end of the string checking each character. 
    for (i=0; i< (myLength - 1); i++)
    {
        if (myString.charAt(i) != myString.charAt(j)) return false;
        
        j--;

    }

    return true;
}

Note: This solution does not check for spaces. While "STAR RATS" would return TRUE, "WAS IT A RAT I SAW" will return false. Re-write the program so that it accepts strings with spaces.