// Program to test solutions to problem #7 on the cse142 midterm, autumn 2014. // Fill in your solution to checkPrime, then compile and run the program. // Please note that in the output produced by this program, the characters "\n" // represent a line break in the output. import java.util.*; import java.io.*; public class Test7 { public static boolean checkPrime(int n) { // fill in your solution here // you can also rename the parameter above } // this is the sample solution public static boolean checkPrime2(int n) { System.out.print("factors of " + n + " = 1"); int count = 1; for (int i = 2; i <= n; i++) { if (n % i == 0) { System.out.print(", " + i); count++; } } System.out.println(); System.out.println("Total factors = " + count); return count == 2; } public static final int MAX_TEST = 30; public static final String END_TEST_TEXT = "end test"; public static final String TEMP_FILE_NAME = "CSE142_Test8_temporary_file.txt"; private static int count, failCount; private static boolean[] returnOK; public static void main(String[] args) throws FileNotFoundException { returnOK = new boolean[MAX_TEST + 1]; // 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 i = 1; i <= MAX_TEST; i++) { System.out.println(i + " " + isPrime(i)); boolean test1 = checkPrime2(i); boolean test2 = false; try { test2 = checkPrime(i); } catch (Exception e) { System.out.println("threw " + e.getClass()); } System.out.println(END_TEST_TEXT); returnOK[i] = test1 == test2; } System.out.close(); // go through the file to compare pairs of answers System.setOut(old); Scanner input = new Scanner(temp); for (int i = 1; i <= MAX_TEST; i++) { count++; String[] answer = input.nextLine().split(" "); String correct = input.nextLine() + "\\n" + input.nextLine() + "\\n"; String yours = ""; String line = input.nextLine(); while (!line.equals(END_TEST_TEXT)) { yours += line + "\\n"; line = input.nextLine(); } System.out.println("Testing checkPrime(" + answer[0] + ")"); System.out.println("Correct output:"); System.out.println(correct); boolean fail = false; if (correct.equals(yours)) { System.out.println("output passed"); } else { fail = true; System.out.println("Your output:"); System.out.println(yours); } if (returnOK[i]) { System.out.println("return ok"); } else { fail = true; System.out.println("return should have been " + answer[1]); } if (!fail) { System.out.println("passed"); } else { failCount++; System.out.println("failed"); } System.out.println(); } // remove the temporary file input.close(); temp.delete(); if (failCount == 0) { System.out.println("passed all tests"); } else { System.out.println("failed " + failCount + " of " + count + " tests"); } } public static boolean isPrime(int n) { for (int i = 2; i <= Math.sqrt(n); i++) { if (n % i == 0) { return false; } } return n != 1; } }