// Program to test solutions to problem #2 on the cse143 midterm, spring 2011. // Fill in your solution to replace, then compile and run the program. import java.util.*; public class Test2 { public static String replace(String s, char target, char replacement) { // fill in your solution here // you can also rename the parameters above } // this is the sample solution public static String replace2(String s, char target, char replacement) { if (s.length() == 0) return ""; else { String rest = replace2(s.substring(1), target, replacement); if (s.charAt(0) == target) return replacement + rest; else return s.charAt(0) + rest; } } public static void main(String[] args) { test("to be or not to be", 'e', 'o'); test("to be or not to be", 'o', '-'); test("to be or not to be", 'm', '!'); test("Mississippi", 'i', 'e'); test("hah!", 'h', '*'); test("Hah!", 'h', '*'); test("g", 'g', 'h'); test("g", 'h', 'g'); test("", 'g', 'h'); test("abaabbaaabbbaaaabbbb", 'a', '-'); test("abaabbaaabbbaaaabbbb", 'b', '-'); test("aaa", 'a', '-'); test("aaa", 'x', '-'); } public static void test(String s, char target, char replacement) { System.out.println("testing replace(\"" + s + "\", '" + target + "', '" + replacement + "')"); String result1 = replace2(s, target, replacement); boolean fail = false; try { String result2 = replace(s, target, replacement); if (!result1.equals(result2)) { fail = true; System.out.println("result should be \"" + result1 + "\", yours = \"" + result2 + "\""); } } catch (RuntimeException e) { System.out.println("threw " + e); fail = true; } if (!fail) { System.out.println("passed"); } else { System.out.println("failed"); } System.out.println(); } }