package example; /** * The class to demonstrate ComTest as a test and design tool. * In this example we have side effect that makes * the testing a bit more complex. * * Suppose our problem is to do some linguistic research * and find what are the most popular three first vowels from * every verse in Finish national poetry Kalevala. * The first song of Kalevala begins like: *
* Mieleni minun tekevi, aivoni ajattelevi * lähteäni laulamahan, saa'ani sanelemahan, * sukuvirttä suoltamahan, lajivirttä laulamahan. * Sanat suussani sulavat, puhe'et putoelevat, * kielelleni kerkiävät, hampahilleni hajoovat. ** At the beginning we will need to read the file kalevala.txt * and then take every verse and extract there 3 first vowels. * To extract the 3 first vowels we might need a function * extract3FirstVowels(s). But to make it a bit more generic * we may send the number 3 as a parameter. And to make it more general * we might send also the list of chars to extract as a parameter. * So we need a function extractChars(s,n,letters) * @author vesal * @version 8.6.2010 * */ public class TakeCharsReady { /** * Take from s the n first chars that are in the list of letters and return them. * @param s where to take letters * @param n how many letters to take at max * @param letters set of letters we are looking * @return n first chars belonging to set letters * * @example *
* StringBuilder s = new StringBuilder("Mieleni minun tekevi"); * extractChars(s,3,"aeiouyåäö") === "iee"; s.toString() === "Mlni minun tekevi"; * extractChars(s,3,"xyz") === ""; s.toString() === "Mlni minun tekevi"; * extractChars(s,4,"klmn") === "Mlnm"; s.toString() === "i inun tekevi"; * extractChars(s,4,"e") === "ee"; s.toString() === "i inun tkvi"; ** * @example *
* StringBuilder s; * s = new StringBuilder($s); * extractChars(s,$n,$letters) === $result; s.toString() === $left; * * $s | $n | $letters | $result | $left * ------------------------------------------------------------------------------- * "Mieleni minun tekevi" | 3 | "aeiouyåäö" | "iee" | "Mlni minun tekevi" * --- | 3 | "xyz" | "" | "Mlni minun tekevi" * --- | 4 | "klmn" | "Mlnm" | "i inun tekevi" * --- | 4 | "e" | "ee" | "i inun tkvi" **/ public static String extractChars(StringBuilder s, int n, String letters) { StringBuilder result = new StringBuilder(); String uletters = letters.toUpperCase(); int i = 0; while ( i < s.length() && result.length() < n ) { char c = s.charAt(i); if ( uletters.indexOf(Character.toUpperCase(c)) >= 0 ) { // found the letter result.append(c); s.deleteCharAt(i); } else { // not found, move to the next one i++; } } return result.toString(); } /** * @param args not used */ public static void main(String[] args) { StringBuilder s = new StringBuilder("Mieleni minun tekevi"); String vowels3 = extractChars(s,3,"aeiouyåäö"); System.out.println("Three first vovels are " + vowels3 + " and there are left " + s); } }