Wednesday April 1, 2015, 16:00-17:15 Lab 01 Version F
Programming question
Implement the Test5F class. A skeleton can be found
here. The API can be found
here.
You have to put your Test5F 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;
import java.util.List;
public class Test5F
{
/**
* Returns the number of a's in the given string.
*
* @param word a string
* @pre. word != null
* @return the number of a's in the given string.
*/
public static int numberOfAs(String word)
{
int number;
if (word.length() == 0)
{
number = 0;
}
else
{
number = word.charAt(0) == 'a' ? 1 : 0;
number += Test5F.numberOfAs(word.substring(1));
}
return number;
}
/**
* Tests whether all strings of the given list have the same
* length.
*
* @param sentence a list of strings
* @pre. sentence != null
* @return true if all strings of the given list have the same
* length, false otherwise.
*/
public static boolean sameLength(List sentence)
{
boolean same;
if (sentence.size() <= 1)
{
same = true;
}
else
{
same = sentence.get(0).length() == sentence.get(1).length()
&& Test5F.sameLength(sentence.subList(1, sentence.size()));
}
return same;
}
}
Other questions
Consider the following method.
/**
* Returns n + 4, where n is the given integer.
*
* @param n an integer.
* @pre. 0 <= n && n <= 100.
* @return n + 4.
*/
public static int recursive(int n)
{
if (n == 100)
{
return 104;
}
else if (n == 0)
{
return 4;
}
else if (2 * n <= 100)
{
return recursive(2 * n) / 2 + 2;
}
else
{
return recursive(n + 1) - 1;
}
}