Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Please use Java. Thank you! In this assignment, you will write seven static meth

ID: 3903869 • Letter: P

Question

Please use Java.

Thank you!

In this assignment, you will write seven static methods in a single class named
StringHelper as described below, following the Recursion Rules specified. You
will write a test program called StingHelperTester that will test each method in
StringHelper.
Attached is sample code (NonRecursiveStringHelper.java) to provide you
with a class to write tests against for this assignment. Note that the implementations
in the sample do not use recursion and use String class methods your solutions
are not permitted to use (such as toString), and may not be correct around edge
cases (such as null inputs). I recommend comparing your recursive results to these
and the specifications below when debugging your code.
Specification
Define a class named StringHelper that contains the following seven static
methods. You are to use a public/private method pattern.
String valueOf(int num)
Write a recursive method called valueOf that takes an integer num, and returns
the String that is the String representation of that number. Each recursive call
will add at most one character to the resulting string.
For example, valueOf(1234) returns the String "1234", and valueOf(-123)
returns the String "-123".
Hint: the modulo and division operators will help you break up the integer value into
its individual digits.
Your solution must follow the rules below. Each recursive call will add at most one
digit to the string.
String toUpperCase(String str)
Write a recursive method named toUpperCase that takes a String and returns the
uppercase form of the input string. That is, any instance of the characters 'a'-'z' is
replaced by the corresponding character 'A'-'Z', and all other characters are
unchanged.
Your implementation must follow the Recursion Rules specified below. Each recursive
call will add at most one character to the resulting string.
Pre: Throw an IllegalArgumentException if passed a null value.
boolean startsWith(String str, String prefix)
Write a recursive method named startsWith that takes two strings, a string and a
prefix, and returns true if the string starts with the prefix, and false otherwise.
indexOf may not be used. Each recursive call will check at most one character in
the string.
Pre/Post: A null or empty prefix always results in a true result; a null or empty string
with a non-empty prefix will always result in a false result.
String replace(String str, char oldChar, char newChar)
Write a recursive method named replace that takes a string and two characters,
and returns a new string that is the same as the input string except that all instances
of oldChar are replaced by newChar.
indexOf cannot be used on the input string.
A null or empty input string, or one that does not contain oldChar, is returned
unchanged.
boolean equals(String str1, String str2)
Write a recursive method named equals that takes two strings and returns true if
the two strings hold the same values, and false otherwise. indexOf may not be
used. Each recursive call will check at most one character in the string.
Pre: If both are null, this returns true; otherwise if only one is null, false would be
returned.
int compareTo(String str1, String str2)
Write a recursive method named compareTo that takes two strings and returns 0 if
the two strings hold the same values, a negative value if str1's value is less than
str2's in dictionary ordering, and a positive value if str1's value is greater than str2's
in dictionary ordering. indexOf may not be used. Each recursive call will check at
most one character in the string.
Challenge: return the same values that String's compareTo returns (see the official
String.compareTo javadoc)
Pre: If either is null, a IllegalArgumentException is returned.
int countChar(String str, char ch)
Write a recursive method named countChar that takes a string and a character
and returns the count of the number of occurrences of the character in the string.
indexOf may not be used. Each recursive call will check at most one character in
the string.
Pre: If str is null, a 0 is returned.
Recursion Rules
The methods must not use any loops at all, and must use recursion. You cannot call
the existing String methods by the same name as the ones here, and you cannot call
indexOf, toString, or toCharArray. You must not use StringBuilder or
StringBuffer in your code. (Hint: charAt is the most useful call for solving this,
and substring for the recursion.) Your recursive method will generally take the first
character of an input string and then recurse on the remaining portion of the string.
Your class must not have any instance or static fields, but may define constants to
satisfy the code conventions. You may write private helper methods if additional
parameters are useful or to limit checks that only need to be made once.
Challenge: Consider performance, do the recursion without using substring.
Tests
Write tests for your seven methods. Name this class StringHelperTest.java.
Your tests need to validate these requirements. That means they need to ensure the
methods work correctly, and that they do not work incorrectly. Note that the sample,
non-recursive StringHelper provided would actually fail some of the tests as it is
missing some of the finer details specified here. You may write more than one test
for each method, in fact it would be unusual if you did not.

Codes needed:

NonRecursiveStringHelper.java

package CS143;

public class NonRecursiveStringHelper {

public static String valueOf(int num) {

return ""+num;

}

public static String toUpperCase(String str) {

return str.toUpperCase();

}

public static boolean startsWith(String str, String prefix) {

return str.startsWith(prefix);

}

public static String replace(String str, char oldChar, char newChar) {

return str.replace(oldChar,newChar);

}

public static boolean equals(String str1, String str2) {

return str1.equals(str2);

}

public static int compareTo(String str1, String str2) {

return str1.compareTo(str2);

}

public static int countChar(String str, char ch) {

int count = 0;

for (int i=0; i<str.length(); i++) {

if (str.charAt(i) == ch) {

count++;

}

}

return count;

}

}

StringHelper.java

package CS143;

// These are the recursive helper methods

public class StringHelper {

public static String valueOf(int num) {

return "";

}

public static String toUpperCase(String str) {

return str;

}

public static boolean startsWith(String str, String prefix) {

return false;

}

public static String replace(String str, char oldChar, char newChar) {

return "";

}

public static boolean equals(String str1, String str2) {

return false;

}

public static int compareTo(String str1, String str2) {

return 0;

}

// Write a recursive method named countChar that takes a string and a

// character and returns the count of the number of occurrences of the

// character in the string. indexOf may not be used. Each recursive

call

// will check at most one character in the string.

public static int countChar(String str, char ch) {

if (str == null) {

return 0;

}

return countCharHelper(str, ch);

}

private static int countCharHelper(String str, char ch) {

return 0;

}

}

StringHelperTester.java

package CS143;

public class StringHelperTester {

public static void main(String[] args) {

// tests for valueOf

// tests for toUpperCase

// tests for startsWith

// tests for replace

// tests for equals

// tests for compareTo

// tests for countChar

String testStr = "foobar";

// expected results:

int count = NonRecursiveStringHelper.countChar(testStr,

'o');

// test 1

int countr = StringHelper.countChar(testStr, 'o');

if (count == countr) {

System.out .println("Test #1 Succeeded, Got

Expected = " + count);

}

else {

System.out .println("Test#2 Failed, Got = " +

countr);

}

// test #2 precondition str == null

// this is a case where the non-recursive method fails

try {

count =

NonRecursiveStringHelper.countChar(null, 'o');

}

catch (Exception ex) {

ex.getMessage();

}

// Test #2: test whether the recursive method produces a

0

try {

count = StringHelper.countChar(null, 'o');

if (count == 0) {

System.out .println("Test#2 Succeeded,

Got Expected = " + count);

}

else {

System.out .println("Test #2 Failed,

Got = " + countr);

}

}

catch (Exception ex) {

System.out .println("Test #2 Failed, Caught

Exception ");

ex.getMessage();

}

// Test #3 Character is not found in String

count = NonRecursiveStringHelper.countChar(testStr, 'x');

countr = StringHelper.countChar(testStr, 'x');

if (count == countr) {

System.out .println("Test #3 Succeeded, Got

Expected = " + count);

}

else {

System.out .println("Test #3 Failed, Got = "

+ countr);

}

// Test #4: What happens when you pass a zero-length string

count = NonRecursiveStringHelper.countChar("", 'o');

countr = StringHelper.countChar("", 'o');

if (count == countr) {

System.out .println("Test #4 Succeeded, Got

Expected = " + count);

}

else {

System.out .println("Test #4 Failed, Got = "

+ countr);

}

}

}

Explanation / Answer

// StringHelper.java

public class StringHelper {

                /**

                *

                * @return the String that is the String representation of that number

                */

                public String valueOf(int num) {

                                if (num < 0) {

                                                //appending - symbol

                                                return "-" + valueOf(-num);

                                }

                                if (num > 0) {

                                                int digit = num % 10;

                                                num = num / 10;

                                                //appending digit at the end

                                                return valueOf(num) + digit;

                                }

                                return "";

                }

                /**

                *

                * @return the uppercase form of the input string

                */

                public String toUpperCase(String str) {

                                if (str == null) {

                                                throw new IllegalArgumentException();

                                }

                                if (str.length() > 0) {

                                                char c = str.charAt(0);

                                                if (c >= 'a' && c <= 'z') {

                                                                int i = c - 'a';

                                                                // converting to upper case

                                                                char upper = (char) ('A' + i);

                                                                return upper + toUpperCase(str.substring(1));

                                                } else {

                                                                return c + toUpperCase(str.substring(1));

                                                }

                                }

                                return "";

                }

                /**

                *

                * @return true if the string starts with the prefix, and false otherwise.

                */

                public boolean startsWith(String str, String prefix) {

                                //checking base conditions

                                if (prefix == null || prefix.length() == 0) {

                                                return true;

                                }

                                if (str == null || str.length() == 0) {

                                                return false;

                                }

                                if (str.charAt(0) == prefix.charAt(0)) {

                                                return startsWith(str.substring(1), prefix.substring(1));

                                } else {

                                                return false;

                                }

                }

                /**

                *

                * @return a new string that is the same as the input string except that all

                *         instances of oldChar are replaced by newChar

                */

                public String replace(String str, char oldChar, char newChar) {

                                if (str == null || str.length() == 0) {

                                                return str;

                                }

                                char c = str.charAt(0);

                                if (c == oldChar) {

                                                //replacing

                                                c = newChar;

                                }

                                return c + replace(str.substring(1), oldChar, newChar);

                }

                /**

                * @return true if the two strings hold the same values, and false otherwise

                */

                public boolean equals(String str1, String str2) {

                                //checking base conditions

                                if (str1 == null && str2 == null) {

                                                return true;

                                } else if (str1 == null || str2 == null) {

                                                return false;

                                } else if (str1.length() != str2.length()) {

                                                return false;

                                }

                                if (str1.length() == 0) {

                                                return true;//same strings

                                }

                                char c1 = str1.charAt(0);

                                char c2 = str2.charAt(0);

                                if (c1 == c2) {

                                                return equals(str1.substring(1), str2.substring(1));

                                }

                                return false;

                }

                /**

                * @return 0 if the two strings hold the same values, a negative value if

                *         str1's value is less than str2's in dictionary ordering, and a

                *         positive value if str1's value is greater than str2's in

                *         dictionary ordering

                */

                public int compareTo(String str1, String str2) {

                                if (str1 == null || str2 == null) {

                                                throw new IllegalArgumentException();

                                }

                                if (str1.length() > 0 && str2.length() > 0) {

                                                char c1 = str1.charAt(0);

                                                char c2 = str2.charAt(0);

                                                if (c1 < c2) {

                                                                return -1;//str1 before str2

                                                } else if (c1 > c2) {

                                                                return 1;//str2 before str1

                                                } else {

                                                                return compareTo(str1.substring(1), str2.substring(1));

                                                }

                                } else if (str1.length() < str2.length()) {

                                                return -1;

                                } else if (str1.length() > str2.length()) {

                                                return 1;

                                }

                                return 0;// equal strings

                }

                /**

                * @return the count of the number of occurrences of the character in the

                *         string

                */

                public int countChar(String str, char ch) {

                                if (str == null) {

                                                return 0;

                                }

                                if (str.length() > 0) {

                                                char c = str.charAt(0);

                                                if (c == ch) {

                                                                return 1 + countChar(str.substring(1), ch);

                                                } else {

                                                                return countChar(str.substring(1), ch);

                                                }

                                }

                                return 0;

                }

}

// StringHelperTester.java

public class StringHelperTester {

                public static void main(String[] args) {

                                StringHelper stringHelper = new StringHelper();

                                // tests for valueOf

                                System.out.println("Testing valueOf:");

                                System.out.println(stringHelper.valueOf(1234) + ", Expected: 1234");

                                System.out.println(stringHelper.valueOf(-557) + ", Expected: -557");

                                // tests for toUpperCase

                                System.out.println(" Testing toUpperCase:");

                                System.out.println(stringHelper.toUpperCase("abcd1234X*&A")

                                                                + ", Expected: ABCD1234X*&A");

                                // tests for startsWith

                                System.out.println(" Testing startsWith:");

                                System.out.println(stringHelper.startsWith("hello", "hell")

                                                                + ", Expected: true");

                                System.out.println(stringHelper.startsWith("laurel", "yanny")

                                                                + ", Expected: false");

                                // tests for replace

                                System.out.println(" Testing replace:");

                                System.out.println(stringHelper.replace("hello", 'l', 'x')

                                                                + ", Expected: hexxo");

                                System.out.println(stringHelper.replace("Amazing", 'x', 'y')

                                                                + ", Expected: Amazing");

                                // tests for equals

                                System.out.println(" Testing equals:");

                                System.out.println(stringHelper.equals("foobar", "foobar")

                                                                + ", Expected: true");

                                System.out.println(stringHelper.equals("foobar", "foo bar")

                                                                + ", Expected: false");

                                System.out

                                                                .println(stringHelper.equals(null, null) + ", Expected: true");

                                // tests for compareTo

                                System.out.println(" Testing compareTo:");

                                System.out.println(stringHelper.compareTo("bat", "football")

                                                                + ", Expected: -1");

                                System.out.println(stringHelper.compareTo("Kevin", "Kevin")

                                                                + ", Expected: 0");

                                System.out.println(stringHelper.compareTo("Kevin ABC", "Kevin")

                                                                + ", Expected: 1");

                                // tests for countChar

                                System.out.println(" Testing countChar:");

                                System.out.println(stringHelper.countChar("hello world", 'l')

                                                                + ", Expected: 3");

                                System.out.println(stringHelper.countChar("hello world", 'z')

                                                                + ", Expected: 0");

                }

}