// Program to test solutions to problem #8 on the cse142 midterm, winter 2011. // Fill in your solution to numWords, then compile and run the program. import java.util.*; public class Test8 { 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; } public static void main(String[] args) { test("how many words here?"); test("to be or not to be, that is the question"); test(" how about merry-go-round "); test(" !&$%--$$!!*() foo_bar_baz "); test("x"); test(" "); test(""); } public static void test(String s) { System.out.println("testing \"" + s + "\""); int num1 = 0; boolean fail = false; try { num1 = numWords(s); } catch (RuntimeException e) { System.out.println("threw " + e); fail = true; } int num2 = numWords2(s); System.out.println("correct = " + num2 + ", theirs = " + num1); if (!fail && num1 == num2) { System.out.println("PASS"); } else { System.out.println("FAIL"); } System.out.println(); } }