// Program to test solutions to problem #2 on the cse143 midterm, spring 2012. // Fill in your solution to printDashed, 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 printDashed(int n) { // fill in your solution here // you can also rename the parameter above } // this is the sample solution public static void printDashed2(int n) { if (n < 0) { System.out.print("-"); printDashed2(-n); } else if (n < 10) { System.out.print(n); } else { printDashed2(n / 10); System.out.print("-" + n % 10); } } 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); int[] data = {-1234567, -834, -17, -4, 0, 6, 42, 983, 29348, 1234567}; for (int n : data) { System.out.println(n); try { printDashed2(n); System.out.println(); } catch (Exception e) { System.out.println("threw " + e.getClass()); } try { printDashed(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(); } }