package test5;
import java.util.List;
public class Test5D {
private Test5D() {
}
/**
* Returns a string of length n formed by alternating the
* characters first and second. Some examples:
*
* Test5D.alternate('*', '-', 0) returns the string ""
* Test5D.alternate('*', '-', 1) returns the string "*"
* Test5D.alternate('*', '-', 2) returns the string "*-"
* Test5D.alternate('*', '-', 3) returns the string "*-*"
* Test5D.alternate('*', '-', 4) returns the string "*-*-"
*
* @param first
* the first character of the repeating pattern
* @param second
* the second character of the repeating pattern
* @param n
* the length of the desired string
* @pre. n >= 0
* @return the string of alternating first and second characters
*/
public static String alternate(char first, char second, int n) {
String s = "";
if (n == 0) {
s = "";
} else if (n == 1) {
s = "" + first;
} else {
s = s + first + second + Test5D.alternate(first, second, n - 2);
}
return s;
}
/**
* Moves the first element f of t down the list
* until it reaches the first location in the list where the next element is
* greater than or equal to f. For example, if t is
* the list:
*
* [4, 2, 1, 5] then Test5D.moveFirstDown(t)
* rearranges the elements in t to [2, 1, 4, 5] (the
* 4 moves to the spot immediately before the 5).
*
* @param t
* the list to move the first element of
*/
public static void moveFirstDown(List<Integer> t) {
if (t.size() > 1) {
int first = t.get(0);
int second = t.get(1);
if (first > second) {
t.set(0, second);
t.set(1, first);
Test5D.moveFirstDown(t.subList(1, t.size()));
}
}
}
}
Other questions
Consider the following method:
/**
* Returns true if the character c appears in s, and false otherwise.
*
* @param s a string
* @param c a character to search for in s
* @return true if the character c appears in s, and false otherwise.
*/
public static boolean contains(String s, char c) {
int result = false;
if (s.isEmpty()) {
result = false;
}
else if (s.charAt(0) == c) {
result = true;
}
else {
String t = s.substring(1, s.length());
result = contains(t , c);
}
return result;
}