In: Computer Science
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 the algorithms assigned. For example,
don't use String.reverse().
public boolean recursiveContains(char c, String s) returns true if
the String contains the char, otherwise returns false.
Here is the code for this method, which you should use as an
example to see how to write the remaining methods:
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) returns true if
all the characters in the String are identical, otherwise false. If
the String has length less than 2, all the 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.
Test your work using a main() method .(language is java)
:: Solution ::
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"));
}
}
Please rate my answer. Thank you...