// Program to test solutions to problem #2 on the cse143 midterm, winter 2016. // Fill in your solution to printPattern, 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 printPattern(int n) { // fill in your solution here // you can also rename the parameter above } // this is the sample solution public static void printPattern2(int n) { if (n < 0) { throw new IllegalArgumentException(); } else if (n > 0) { if (n == 1) { System.out.print("."); } else if (n / 2 % 2 == 0) { System.out.print("["); printPattern2(n - 2); System.out.print("]"); } else { System.out.print("("); printPattern2(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"; private static int testCount; private static int failCount; 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 = -3; n <= 20; n++) { testCount++; System.out.println(n); try { printPattern2(n); System.out.println(); } catch (Exception e) { System.out.println("threw " + e.getClass().getName()); } try { printPattern(n); System.out.println(); } catch (Exception e) { System.out.println("threw " + e.getClass().getName()); } 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 result:"); System.out.print(correct); if (correct.equals(yours)) { System.out.println("passed"); } else { System.out.println("Your result:"); System.out.print(yours); System.out.println("failed"); failCount++; } System.out.println(); } // remove the temporary file input.close(); temp.delete(); if (failCount == 0) { System.out.println("passed all " + testCount + " tests"); } else { System.out.println("failed " + failCount + " of " + testCount + " tests"); } } }