KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > prefuse > data > parser > DoubleArrayParser


1 package prefuse.data.parser;
2
3 import java.util.StringTokenizer JavaDoc;
4
5 /**
6  * DataParser instance the parses an array of double values from a text string.
7  * Values are expected to be comma separated and can be within brackets,
8  * parentheses, or curly braces.
9  *
10  * @author <a HREF="http://jheer.org">jeffrey heer</a>
11  */

12 public class DoubleArrayParser implements DataParser {
13     
14     /**
15      * Returns double[].class.
16      * @see prefuse.data.parser.DataParser#getType()
17      */

18     public Class JavaDoc getType() {
19         return double[].class;
20     }
21     
22     /**
23      * @see prefuse.data.parser.DataParser#format(java.lang.Object)
24      */

25     public String JavaDoc format(Object JavaDoc value) {
26         if ( value == null ) return null;
27         if ( !(value instanceof double[]) )
28             throw new IllegalArgumentException JavaDoc(
29               "This class can only format Objects of type double[].");
30         
31         double[] values = (double[])value;
32         StringBuffer JavaDoc sbuf = new StringBuffer JavaDoc();
33         sbuf.append('[');
34         for ( int i=0; i<values.length; ++i ) {
35             if ( i > 0 ) sbuf.append(", ");
36             sbuf.append(values[i]);
37         }
38         sbuf.append(']');
39         return sbuf.toString();
40     }
41     
42     /**
43      * @see prefuse.data.parser.DataParser#canParse(java.lang.String)
44      */

45     public boolean canParse(String JavaDoc text) {
46         try {
47             StringTokenizer JavaDoc st = new StringTokenizer JavaDoc(text, "\"[](){}, ");
48             while ( st.hasMoreTokens() ) {
49                 Double.parseDouble(st.nextToken());
50             }
51             return true;
52         } catch ( NumberFormatException JavaDoc e ) {
53             return false;
54         }
55     }
56     
57     /**
58      * Parse an int array from a text string.
59      * @param text the text string to parse
60      * @return the parsed integer array
61      * @throws DataParseException if an error occurs during parsing
62      */

63     public Object JavaDoc parse(String JavaDoc text) throws DataParseException {
64         try {
65             StringTokenizer JavaDoc st = new StringTokenizer JavaDoc(text, "\"[](){}, ");
66             double[] array = new double[st.countTokens()];
67             for ( int i=0; st.hasMoreTokens(); ++i ) {
68                 String JavaDoc tok = st.nextToken();
69                 array[i] = Double.parseDouble(tok);
70             }
71             return array;
72         } catch ( NumberFormatException JavaDoc e ) {
73             throw new DataParseException(e);
74         }
75     }
76     
77 } // end of class DoubleArrayParser
78
Popular Tags