logo Practice-It logo

parenthesize

Language/Type: Java recursion recursive programming
Author: Whitaker Brand (on 2014/02/14)

Write a recursive method called parenthesize that takes a String and an integer n as parameters and that prints the string inside n sets of parentheses. For example, this code:

        parenthesize("Joe", 2);
        System.out.println();  // to complete line of output
        parenthesize("The University of Washington", 6);
        System.out.println();  // to complete line of output
        parenthesize("midterm", 1);
        System.out.println();  // to complete line of output

should produce these 3 lines of output:

        ((Joe))
        ((((((The University of Washington))))))
        (midterm)

Your method should throw an IllegalArgumentException if passed a negative number. It could be passed 0, as in:

        parenthesize("CS143, Spring 2010", 0);
        System.out.println();  // to complete line of output

In this case the output would have no (i.e., 0) parentheses:

        CS143, Spring 2010

You are not allowed to construct any structured objects (no array, ArrayList, String, StringBuilder, etc) and you may not use a while loop, for loop, or do/while loop to solve this problem; you must use recursion.

Type your solution here:


This is a method problem. Write a Java method as described. Do not write a complete program or class; just the method(s) above.

You must log in before you can solve this problem.


Log In

If you do not understand how to solve a problem or why your solution doesn't work, please contact your TA or instructor.
If something seems wrong with the site (errors, slow performance, incorrect problems/tests, etc.), please

Is there a problem? Contact a site administrator.