import java.util.*; import java.io.*; // Program to test solutions to problem #9 on the cse143x midterm, fall 2012. // Fill in your solution to printCompact, then compile and run the program. import java.util.*; public class Test9 { public static void printCompact(String s) { // fill in your solution here // you can also rename the parameter above } // this is the sample solution public static void printCompact2(String s) { boolean inWord = false; boolean firstWord = true; for (int i = 0; i < s.length(); i++) { char next = s.charAt(i); if (next == ' ') { inWord = false; } else { // next != ' ' if (!inWord) { inWord = true; if (firstWord) { firstWord = false; } else { System.out.print(' '); } } System.out.print(next); } } System.out.println(); } 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); String[] data = {"this is fun", " four score and seven", "four score and seven ", " four score and seven ", " this string has lots of spaces ", "hello", " how", "are ", " you ", "", " ", " ", " ", " ", " "}; for (String s : data) { System.out.println("\"" + s + "\""); printCompact2(s); try { printCompact(s); System.out.println(); } catch (Exception e) { StackTraceElement[] frames = e.getStackTrace(); int line = frames[frames.length - 2].getLineNumber(); System.out.println("\nthrew " + e + " at line #" + line); } System.out.println(END_TEST_TEXT); } System.out.close(); // go through the file to compare pairs of answers int fail = 0; System.setOut(old); Scanner input = new Scanner(temp); while (input.hasNextLine()) { String s = input.nextLine(); String correct = input.nextLine() + "\\n"; String yours = null; String line = input.nextLine(); while (!line.equals(END_TEST_TEXT)) { if (yours == null) { yours = line; } else { yours += line + "\\n"; } line = input.nextLine(); } System.out.println("Testing with s = " + s); System.out.println("Correct output: \"" + correct + "\""); if (correct.equals(yours)) { System.out.println("passed"); } else { System.out.println("Your output: \"" + yours + "\""); System.out.println("failed"); fail++; } System.out.println(); } if (fail == 0) { System.out.println("all tests passed"); } else { System.out.println("failed " + fail + " tests"); } // remove the temporary file input.close(); temp.delete(); } }