KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > inversoft > verge > examples > madlib > MadLibBuilder


1 /*
2  * Copyright (c) 2003, Inversoft
3  *
4  * This software is distribuable under the GNU Lesser General Public License.
5  * For more information visit gnu.org.
6  */

7 package com.inversoft.verge.examples.madlib;
8
9
10 import java.util.Iterator JavaDoc;
11
12
13 /**
14  * <p>
15  * The class uses the MadLibBean object to create the final text
16  * of the MadLib. This bean contains the users input, as well as
17  * the MadLib object that describesthe MadLib.
18  * </p>
19  *
20  * @author Brian Pontarelli
21  */

22 public class MadLibBuilder {
23
24     /**
25      * Static class
26      */

27     private MadLibBuilder() {
28         // Empty
29
}
30
31
32     /**
33      * Using the information the user entered and that is stored in the MadLibBean
34      * as well as the MadLib object, this builds the final output of the MadLib.
35      *
36      * @param mb The MadLib bean that contains the users input, and the MadLib
37      * Object to use
38      * @return The final output of the MadLib
39      * @throws MadLibException If there was any problem building
40      */

41     public static String JavaDoc buildMadLib(MadLibBean mb) throws MadLibException {
42
43         MadLib madlib = mb.getMadLib();
44         if (madlib == null) {
45             throw new MadLibException("MadLib is null");
46         }
47
48         String JavaDoc rawText = madlib.getRawText();
49         StringBuffer JavaDoc buf = new StringBuffer JavaDoc(rawText.length());
50         int currentIndex = 0;
51         Iterator JavaDoc iter = madlib.getRawMadLibFillins().iterator();
52         while (iter.hasNext()) {
53             MadLibFillin fillin = (MadLibFillin) iter.next();
54
55             buf.append(rawText.substring(currentIndex, fillin.getStartIndex()));
56             if (fillin.isWord()) {
57                 buf.append(mb.getWord(fillin.getIndex()));
58             } else {
59                 buf.append(mb.getNumber(fillin.getIndex()));
60             }
61
62             currentIndex = fillin.getEndIndex() + 1;
63         }
64
65         if (currentIndex < rawText.length()) {
66             buf.append(rawText.substring(currentIndex));
67         }
68
69         return buf.toString();
70     }
71 }
Popular Tags