Wednesday April 1, 2015, 13:00-14:15 Lab 02 Version A
Programming question
Implement the Test5A class. A skeleton can be found
here. The API can be found
here.
You have to put your Test5A class in the test5 package.
You have to use recursion.
The methods charAt, substring and length of the String class might be useful.
package test5;
public class Test5A
{
/**
* Returns the sum of the digits of the given string.
* The sum of the empty string is 0.
*
* @param digits a string consisting of only digits.
* @pre. digits consists of only digits.
* @return the sum of the digits of the given string.
*/
public static int sum(String digits)
{
int sum;
if (digits.length() == 0)
{
sum = 0;
}
else
{
sum = (digits.charAt(0) - '0') + Test5A.sum(digits.substring(1));
}
return sum;
}
/**
* Tests whether the given character occurs an even number of
* times in the given string. The number 0 is even.
*
* @param word a word.
* @pre. word != null
* @param character a character
* @return true if the given character occurs an even number of
* times in the given string, false otherwise.
*/
public static boolean even(String word, char character)
{
boolean even;
if (word.length() == 0)
{
even = true;
}
else
{
if (word.charAt(0) == character)
{
even = !Test5A.even(word.substring(1), character);
}
else
{
even = Test5A.even(word.substring(1), character);
}
}
return even;
}
}
Other questions
Consider the following method.
/**
* Returns 6n + 6, where n is the given integer.
*
* @param n an integer.
* @pre. n >= 0.
* @return 6n + 6.
*/
public static int recursive(int n)
{
if (n == 0)
{
return 6;
}
else if (n % 2 == 0)
{
return 2 * recursive(n / 2) - 6;
}
else
{
return recursive(n - 1) + 6;
}
}