// Program to test solutions to problem #9 on the cse143x midterm, fall 2019. // Fill in your solution to numWords, then compile and run the program. import java.util.*; public class Test9 { public static int numWords(String s) { // fill in your solution here // you can also rename the parameter above } // this is the sample solution public static int numWords2(String s) { int count = 0; boolean inWord = false; for (int i = 0; i < s.length(); i++) { if (s.charAt(i) == ' ') { inWord = false; } else if (!inWord) { count++; inWord = true; } } return count; } private static int count, failCount; private static Random r = new Random(); private static int DISPLAY = 30; public static void main(String[] args) { testOne("how many words here?"); testOne("to be or not to be, that is the question"); testOne(" how about merry-go-round "); testOne(" !&$%--$$!!*() foo_bar_baz "); for (int i = 0; i <= 20; i++) { test(i); } if (failCount == 0) { System.out.println("passed all tests"); } else { if (failCount > DISPLAY) { System.out.println("failed cases exeeds display max of " + DISPLAY); System.out.println(); } System.out.println("failed " + failCount + " of " + count + " tests"); } } public static void testOne(String s) { count++; boolean display = failCount < DISPLAY; int answer = numWords2(s); try { int theirs = numWords(s); if (theirs != answer) { failCount++; if (display) { System.out.println("FAIL (\"" + s + "\")"); System.out.println("correct = " + answer + ", yours = " + theirs); System.out.println(); } } } catch (RuntimeException e) { failCount++; if (display) { int line = e.getStackTrace()[1].getLineNumber(); System.out.println("FAIL (\"" + s + "\")"); System.out.println("threw " + e + " at line #" + line); System.out.println(); } } } public static void test(int len) { test("", len); } public static void test(String s, int count) { if (count > 0) { test(s + character(), count - 1); test(s + " ", count - 1); } else { testOne(s); } } public static char character() { return (char) (r.nextInt(6) + 'x'); } }