// Hw3.java // , , import java.util.Scanner; import java.io.PrintStream; public class Hw3 { //////////////////////////////////////////////////// /// your methods /// (Just print these out!) //////////////////////////////////////////////////// // This method takes two strings and returns true if the two strings // are composed of the same characters (though perhaps in different // numbers and in different orders) -- that is, if every character that // is in the first string, is in the second, and vice versa -- and false otherwise. // This test is case-sensitive, so "ABC" and "abc" do not contain the same // characters. The method returns false if either string is null, but // returns true if both strings are empty (why?). public static boolean sameChars(String s1, String s2) { return false; } // Helper method for sameChars: // Same as sameChars, but only checks if all the chars in s1 // also occur in s2, but not vice versa! public static boolean sameChars1(String s1, String s2) { return false; } // Helper method for sameChars1: // Returns true if the given char occurs in the given String // and false otherwise. Returns false if the String is null. public static boolean contains(String s, char c) { return false; } // Returns the nth Twin Prime, where a a twin prime is a number // p that is prime where (p+2) is also prime. So 3 is a twin prime // (because 5 is prime) and 5 is a twin prime (because 7 is prime), // but 7 is not a twin prime (because 9 is not prime). // If n is less than 1, the method should return -1. // Note: to receive full credit, you must write at least one well-chosen // helper method (and its corresponding test method) for this method. public static int nthTwinPrime(int n) { return 42; } // This method (which has nothing much to do with the value "pi", // but coincidentally shares its name) takes an integer n and returns // the number of prime numbers less than or equal to n.  public static int pi(int n) { return 42; } // This method returns the sum of the first n terms in the harmonic // series:  1/1 + 1/2 + 1/3 + 1/4 + ... // If n is non-positive, the method returns 0. public static double h(int n) { return 42.0; } // This method uses the Harmonic Number function h(n) to estimate the // Prime Counting Function pi(n).  Think about it.  One counts the number // of primes.  The other adds the reciprocals of the integers.  They seem // totally unrelated, but they are in fact very deeply related!  In any case, // this method takes an integer n and if it is greater than 2,  returns the // value (n / (h(n) - 1.5) ), rounded to the nearest integer (and then cast // to an int).  If n is 2 or less, the method returns 0.  public static int estimatedPi(int n) { return 42; } // This method takes an integer n and returns the absolute value of the // difference between the value of our estimation computed by estimatedPi(n) // and the actual number of primes less than or equal to n as computed by pi(n). // If n is 2 or less, then method returns 0.  public static int estimatedPiError(int n) { return 42; } // Returns the number of words in the given file, where a "word" // is whatever is returned by a call to scanner.next(). If the // file does not exist, the method returns -1. public static int wordCount(String filename) { return 42; } // This method takes no parameters and returns the current temperature // (in degrees fahrenheit) in Pittsburgh, as available on this web page: // http://mobile.srh.noaa.gov/port_mp_ns.php?select=3&CityName=Pittsburgh&site=PBZ&State=PA&warnzone=PAZ021 public static int currentTemperature() { return -42; } // This method takes no parameters and plays the number guessing game, // where the user thinks of a number between 0 and 1000 and the computer // guesses it. The user repeatedly instructs the computer if the guess // is too low, correct, or too high, and the computer continues guessing // until it gets the right answer. Each guess must be exactly halfway // between the known limits. public static void numberGuessingGame() { assert(false); } //////////////////////////////////////////////////// /// test methods for your methods /// (Do not print out any code below here!) //////////////////////////////////////////////////// public static void testContains() { System.out.print("Testing contains... "); assert(contains("abcd",'c') == true); assert(contains("abcdabcd",'d') == true); assert(contains("This is a test!",'!') == true); assert(contains("abcd",'e') == false); assert(contains("",'f') == false); assert(contains(null,'g') == false); System.out.println("Passed all tests!"); } public static void testSameChars1() { System.out.print("Testing sameChars1... "); assert(sameChars1("abc", "abc") == true); assert(sameChars1("abc", "cba") == true); assert(sameChars1("ab", "abc") == true); // false for sameChars assert(sameChars1("abc", "ab") == false); assert(sameChars1("ababab", "ababbbb") == true); assert(sameChars1("ababab", "abcabbbb") == true); // false for sameChars assert(sameChars1("abcabbbb", "ababab") == false); assert(sameChars1(null, null) == false); assert(sameChars1(null, "abc") == false); assert(sameChars1("abc", null) == false); System.out.println("Passed all tests!"); } public static void testSameChars() { System.out.print("Testing sameChars... "); assert(sameChars("abc", "abc") == true); assert(sameChars("abc", "cba") == true); assert(sameChars("ab", "abc") == false); // true for sameChars1 assert(sameChars("abc", "ab") == false); assert(sameChars("ababab", "ababbbb") == true); assert(sameChars("ababab", "abcabbbb") == false); // true for sameChars1 assert(sameChars("abcabbbb", "ababab") == false); assert(sameChars(null, null) == false); assert(sameChars(null, "abc") == false); assert(sameChars("abc", null) == false); System.out.println("Passed all tests!"); } public static void testNthTwinPrime() { System.out.print("Testing nthTwinPrime... "); assert(nthTwinPrime(-5) == -1); assert(nthTwinPrime(0) == -1); assert(nthTwinPrime(1) == 3); assert(nthTwinPrime(2) == 5); assert(nthTwinPrime(3) == 11); assert(nthTwinPrime(4) == 17); assert(nthTwinPrime(5) == 29); assert(nthTwinPrime(6) == 41); System.out.println("Passed all tests!"); } public static void testPi() { System.out.print("Testing pi... "); assert(pi(1) == 0); assert(pi(2) == 1); assert(pi(3) == 2); assert(pi(4) == 2); assert(pi(5) == 3); assert(pi(100) == 25); // there are 25 primes in the range [2,100] System.out.println("Passed all tests!"); } public static void testH() { System.out.print("Testing H... "); assert(almostEqual(h(0),0.0)); assert(almostEqual(h(1),1/1.0 )); // h(1) = 1/1 assert(almostEqual(h(2),1/1.0 + 1/2.0 )); // h(2) = 1/1 + 1/2 assert(almostEqual(h(3),1/1.0 + 1/2.0 + 1/3.0)); // h(3) = 1/1 + 1/2 + 1/3 System.out.println("Passed all tests!"); } public static void testEstimatedPi() { System.out.print("Testing estimatedPi... "); assert(estimatedPi(100) == 27); assert(estimatedPi(200) == 46); assert(estimatedPi(300) == 63); System.out.println("Passed all tests!"); } public static void testEstimatedPiError() { System.out.print("Testing estimatedPiError... "); assert(estimatedPiError(100) == 2); // pi(100) = 25, estimatedPi(100) = 27 assert(estimatedPiError(200) == 0); // pi(200) = 46, estimatedPi(200) = 46 assert(estimatedPiError(300) == 1); // pi(300) = 62, estimatedPi(300) = 63 assert(estimatedPiError(400) == 1); // pi(400) = 78, estimatedPi(400) = 79 assert(estimatedPiError(500) == 1); // pi(500) = 95, estimatedPi(500) = 94 System.out.println("Passed all tests!"); } public static void testWordCount() { System.out.print("Testing wordCount... "); // First, create the file "wordCountTest.txt" String filename = "wordCountTest.txt"; PrintStream out = getFilePrintStream(filename); out.println("Roses are red,"); out.println("Violets are blue."); out.println("Some poems rhyme,"); out.println("But not this one."); // now count the words! assert(wordCount(filename) == 13); String nonExistentFilename = "FileThatDoesNotExist.txt"; assert(wordCount(nonExistentFilename) == -1); System.out.println("Passed all tests!"); } public static void testCurrentTemperature() { System.out.print("Testing currentTemperature.. "); int temp = currentTemperature(); assert((temp > 0) && (temp < 100)); System.out.println("Passed all tests (if current temp is " + temp + ")!"); } public static void testNumberGuessingGame() { System.out.print("Testing currentTemperature.. "); System.out.println("Manual testing required!"); System.out.println("---------------------------------------"); numberGuessingGame(); System.out.println("---------------------------------------"); System.out.println(" ... Passed all tests (if it looks right!)"); } //////////////////////////////////////////////////// /// helper methods for reading from files + web //////////////////////////////////////////////////// // Convenient helper method for reading from a file. // Returns null if the file is not found. // You are responsible for using this method, but not // for writing it (neither on homeworks or tests)! public static Scanner getFileScanner(String filename) { Scanner scanner = null; try { scanner = new Scanner(new java.io.File(filename)); } catch (Exception e) { // System.out.println("File not found:" + filename); return null; } return scanner; } // Convenient helper method for writing to a file. // You are responsible for using this method, but not // for writing it (neither on homeworks or tests)! public static PrintStream getFilePrintStream(String filename) { PrintStream out = null; try { out = new PrintStream(new java.io.File(filename)); } catch (Exception e) { System.out.println("Error opening file " + filename); return null; } return out; } // Convenient helper method for reading from a web page (url) as plain text. // Returns null if there are any problems. // You are responsible for using this method, but not // for writing it (neither on homeworks or tests)! public static Scanner getUrlTextScanner(String url) { Scanner scanner = null; try { final StringBuffer sb = new StringBuffer(); java.io.InputStreamReader reader = new java.io.InputStreamReader( new java.net.URL(url).openStream()); javax.swing.text.html.HTMLEditorKit.ParserCallback parser = new javax.swing.text.html.HTMLEditorKit.ParserCallback() { public void handleText(char[] data, int pos) { if (data != null) sb.append(data); } public void handleSimpleTag(javax.swing.text.html.HTML.Tag tag, javax.swing.text.MutableAttributeSet a, int pos) { if (tag.breaksFlow()) sb.append("\n"); } }; new javax.swing.text.html.parser.ParserDelegator().parse(reader, parser, true); scanner = new Scanner(sb.toString()); } catch (Exception e) { System.out.println("Error opening text reader for url: " + url); return null; } return scanner; } //////////////////////////////////////////////////// /// additional test methods and helper methods //////////////////////////////////////////////////// public static boolean almostEqual(double d1, double d2) { double epsilon = 0.000001; return (Math.abs(d2 - d1) < epsilon); } public static void checkAssertsAreEnabled() { boolean assertsEnabled = false; try { assert(false); } catch (Throwable t) { assertsEnabled = true; } if (!assertsEnabled) throw new RuntimeException("assert statements not enabled!"); } public static void testAll() { testContains(); testSameChars1(); testSameChars(); testNthTwinPrime(); testPi(); testH(); testEstimatedPi(); testEstimatedPiError(); testWordCount(); testCurrentTemperature(); testNumberGuessingGame(); } //////////////////////////////////////////////////// /// main method //////////////////////////////////////////////////// public static void main(String[] args) { checkAssertsAreEnabled(); testAll(); } }