In: Computer Science
Using Java
Write the class RecursiveProbs, with the methods listed below. Write all the methods using recursion, NOT LOOPS. You may use JDK String Methods like substring() and length(), but do not use the JDK methods to avoid coding algorithms assigned. For example, don’t use String.revers().
public boolean recursiveContains(char c, String s) {
if (s.length() == 0)
return false;
if (s.charAt(s.length() - 1) == c)
return true;
else
return recursiveContains(c, s.substring(0, s.length() - 1));
}
public boolean recursiveAllCharactersSame(String s) return true if all the characters in the String are identical, otherwise false. if the String has length less than 2, all characters are identical.
public String recursiveHead(int n, String s) returns the substring of s beginning with the first character and ending with the character at n-1; in other words, it returns the first n characters of the String. Return empty String("") in cases in which n is zero or negative or exceeds the length of s.
Write either a main() or a JUnit test case for test
CODE
public class Main {
public static boolean recursiveContains(char c, String s) {
if (s.length() == 0)
return false;
if (s.charAt(s.length() - 1) == c)
return true;
else
return recursiveContains(c, s.substring(0, s.length() - 1));
}
public static boolean recursiveAllCharactersSame(String s) {
if (s == null || s.length() < 2) {
return true;
}
return s.charAt(0) == s.charAt(1) && recursiveAllCharactersSame(s.substring(1));
}
public static String recursiveHead(int n, String s) {
if (n <= 0 || n > s.length()) {
return "";
}
return recursiveHead(n-1, s) + s.charAt(n-1);
}
public static void main(String[] args) {
System.out.println(recursiveContains('h', "hello world"));
System.out.println(recursiveContains('a', "hello world"));
System.out.println(recursiveAllCharactersSame("aaaaa"));
System.out.println(recursiveAllCharactersSame("aaaab"));
System.out.println(recursiveHead(8, "hello world"));
}
}