import java.util.*; import java.io.*; public class Q8Verifier { // enter student solution here public static int countWords(String str) { return 0; } public static String[] testCases = { "", " ", " ", " ", " simple ", " simple2 ", "no space at start ", "no space at start2 ", " no space at end", " no space at end2", "no spaces on either end", "oneword", " lots of airy space in this one", "punctuat!on", "x", "xyx" }; public static void main(String[] args) { int[] results = {0, 0, 0}; // correct, incorrect, error // This loop generates 100 random Strings to test, // only uncomment if you want to test if your solution is // ~perfect~ and it passes all other tests. /* for (int i = 0; i < 100; i++) { for (int j = 0; j < 10; j++) { String s = generate(i); runTest(s, results); } } */ for (int i = 0; i < testCases.length; i++) { runTest(testCases[i], results); } results(results); } // runs a test over the given string, adds a tally in the results // array as to whether the test passed, failed, or threw exception private static void runTest(String s, int[] results) { System.out.println("Testing string: '" + s + "'"); int expected = solution(s); int actual = -1; try { actual = countWords(s); } catch (Exception e) { System.out.println(" EXCEPTION : " + e.getMessage() + " on input string '" + s + "'"); results[2]++; } if (expected == actual) { results[0]++; } else { results[1]++; System.out.println("INCORRECT: on input string '" + s + "' expected = '" + expected + "', actual = '" + actual + "'"); } } // generate a random string of given length // chooses between random letters and spaces. // tries to generate long sequences by preferring // to stay on space/letter private static String generate(int length) { String s = ""; boolean space = Math.random() > 0.5; for (int i = 0; i < length; i++) { if (space) { s += " "; space = Math.random() > 0.6; } else { s += randLetter(); space = Math.random() > 0.9; } } return s; } // print out results, based on counts in results array // 0 - count correct // 1 - count incorrect // 2 - count exception (also incorrect) private static void results(int[] results) { if (results[1] == 0 && results[2] == 0) { System.out.println("All tests passed (" + results[0] + ")"); } else { System.out.println("Passed " + results[0]); System.out.println("Failed " + results[1]); System.out.println("Exception " + results[2]); } System.out.println(); } // ascii chars 33 - 126 are printable private static char randLetter() { return (char) (r.nextInt(94) + 33); } private static int solution(String line) { int count = 0; boolean inWord = false; for (int i = 0; i < line.length(); i++) { char ch = line.charAt(i); if (ch == ' ') { if (inWord) { count++; } inWord = false; } else { inWord = true; } } if (inWord) { count++; } return count; } public static Random r = new Random(); }