// Program to test solutions to problem #2 on the cse143 midterm, fall 2011. // Fill in your solution to writeNumbers, 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 writeNumbers(int n) { // fill in your solution here // you can also rename the parameter above } // this is the sample solution public static void writeNumbers2(int n) { if (n < 1) throw new IllegalArgumentException(); else if (n == 1) System.out.print(1); else if (n % 2 == 1) { System.out.print(n + ", "); writeNumbers2(n - 1); } else { writeNumbers2(n - 1); System.out.print(", " + n); } } 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 { File temp = new File(TEMP_FILE_NAME); PrintStream out = new PrintStream(temp); PrintStream old = System.out; System.setOut(out); for (int i = -2; i <= 10; i++) { System.out.println(i); try { writeNumbers2(i); System.out.println(); } catch (Exception e) { System.out.println("threw " + e.getClass()); } try { writeNumbers(i); System.out.println(); } catch (Exception e) { System.out.println("threw " + e.getClass()); } System.out.println(END_TEST_TEXT); } System.out.close(); 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(); } input.close(); temp.delete(); } }