// Program to test solutions to problem #2 on the cse143 midterm, winter 2014. // Fill in your solution to showSplit, then compile and run the program. // Note: if you generate infinite recursion, it might leave behind a temporary // file on your directory. You can delete this file. import java.util.*; import java.io.*; public class Test2 { public static void showSplit(int n) { // fill in your solution here // you can also rename the parameter above } // this is the sample solution public static void showSplit2(int n) { if (n < 0) { throw new IllegalArgumentException(); } else if (n <= 1) { System.out.print(n); } else { System.out.print(n + " = ("); showSplit2(n / 2 + n % 2); System.out.print(", "); showSplit2(n / 2); System.out.print(")"); } } public static final String END_TEST_TEXT = "end test"; public static final String TEMP_FILE_NAME = "CSE143_Test2_temporary_file.txt"; public static void main(String[] args) throws FileNotFoundException { // create an output file with correct answers and student answers File temp = new File(TEMP_FILE_NAME); PrintStream out = new PrintStream(temp); PrintStream old = System.out; System.setOut(out); for (int n = 0; n <= 20; n++) { System.out.println(n); try { showSplit2(n); System.out.println(); } catch (Exception e) { System.out.println("threw " + e.getClass()); } try { showSplit(n); System.out.println(); } catch (Exception e) { System.out.println("threw " + e.getClass()); } System.out.println(END_TEST_TEXT); } System.out.close(); // go through the file to compare pairs of answers System.setOut(old); Scanner input = new Scanner(temp); while (input.hasNextLine()) { int n = Integer.parseInt(input.nextLine()); String correct = input.nextLine() + "\n"; String yours = ""; for (;;) { String line = input.nextLine(); if (line.equals(END_TEST_TEXT)) break; yours += line + "\n"; } System.out.println("Testing with n = " + n); System.out.println("Correct output:"); System.out.print(correct); if (correct.equals(yours)) { System.out.println("passed"); } else { System.out.println("Your output:"); System.out.print(yours); System.out.println("failed"); } System.out.println(); } // remove the temporary file input.close(); temp.delete(); } }