Example usage for java.lang StringBuffer length

List of usage examples for java.lang StringBuffer length

Introduction

In this page you can find the example usage for java.lang StringBuffer length.

Prototype

@Override
    public synchronized int length() 

Source Link

Usage

From source file:MainClass.java

public static void main(String[] arg) {
    StringBuffer newString = new StringBuffer("abcde1234567890");

    System.out.println(newString.capacity());
    System.out.println(newString.length());
    System.out.println(newString);

    newString.setLength(8);//from   w w w .ja v  a  2 s  .c om

    System.out.println(newString.capacity());
    System.out.println(newString.length());
    System.out.println(newString);

}

From source file:Main.java

public static void main(String args[]) {
    StringBuffer sb = new StringBuffer();
    sb.ensureCapacity(100);//from   ww  w  . j  ava  2s  . c  o  m
    sb.append("java2s.com");
    System.out.println(sb.capacity());
    System.out.println(sb.length());
    System.out.println(sb.toString());

}

From source file:Main.java

public static void main(String args[]) {
    StringBuffer buffer = new StringBuffer("hello there");

    System.out.printf("buffer = %s\n", buffer.toString());
    System.out.printf("Character at 0: %s\nCharacter at 4: %s\n\n", buffer.charAt(0), buffer.charAt(4));

    char charArray[] = new char[buffer.length()];
    buffer.getChars(0, buffer.length(), charArray, 0);
    System.out.print("The characters are: ");

}

From source file:MainClass.java

public static void main(String args[]) {
    StringBuffer buffer = new StringBuffer("hello there");

    System.out.printf("buffer = %s\n", buffer.toString());
    System.out.printf("Character at 0: %s\nCharacter at 4: %s\n\n", buffer.charAt(0), buffer.charAt(4));

    char charArray[] = new char[buffer.length()];
    buffer.getChars(0, buffer.length(), charArray, 0);
    System.out.print("The characters are: ");

    for (char character : charArray)
        System.out.print(character);

    buffer.setCharAt(0, 'H');
    buffer.setCharAt(6, 'T');
    System.out.printf("\n\nbuf = %s", buffer.toString());

    buffer.reverse();/*from www.  j a  v  a  2  s . c  o m*/
    System.out.printf("\n\nbuf = %s\n", buffer.toString());
}

From source file:TextVerifyInputFormatDate.java

public static void main(String[] args) {
    Display display = new Display();
    Shell shell = new Shell(display);
    shell.setLayout(new GridLayout());
    final Text text = new Text(shell, SWT.BORDER);
    text.setText("YYYY/MM/DD");
    ;/*from w ww .  j a  v  a2s  .  com*/
    final Calendar calendar = Calendar.getInstance();
    text.addListener(SWT.Verify, new Listener() {
        boolean ignore;

        public void handleEvent(Event e) {
            if (ignore)
                return;
            e.doit = false;
            StringBuffer buffer = new StringBuffer(e.text);
            char[] chars = new char[buffer.length()];
            buffer.getChars(0, chars.length, chars, 0);
            if (e.character == '\b') {
                for (int i = e.start; i < e.end; i++) {
                    switch (i) {
                    case 0: /* [Y]YYY */
                    case 1: /* Y[Y]YY */
                    case 2: /* YY[Y]Y */
                    case 3: /* YYY[Y] */ {
                        buffer.append('Y');
                        break;
                    }
                    case 5: /* [M]M */
                    case 6: /* M[M] */ {
                        buffer.append('M');
                        break;
                    }
                    case 8: /* [D]D */
                    case 9: /* D[D] */ {
                        buffer.append('D');
                        break;
                    }
                    case 4: /* YYYY[/]MM */
                    case 7: /* MM[/]DD */ {
                        buffer.append('/');
                        break;
                    }
                    default:
                        return;
                    }
                }
                text.setSelection(e.start, e.start + buffer.length());
                ignore = true;
                text.insert(buffer.toString());
                ignore = false;
                text.setSelection(e.start, e.start);
                return;
            }

            int start = e.start;
            if (start > 9)
                return;
            int index = 0;
            for (int i = 0; i < chars.length; i++) {
                if (start + index == 4 || start + index == 7) {
                    if (chars[i] == '/') {
                        index++;
                        continue;
                    }
                    buffer.insert(index++, '/');
                }
                if (chars[i] < '0' || '9' < chars[i])
                    return;
                if (start + index == 5 && '1' < chars[i])
                    return; /* [M]M */
                if (start + index == 8 && '3' < chars[i])
                    return; /* [D]D */
                index++;
            }
            String newText = buffer.toString();
            int length = newText.length();
            StringBuffer date = new StringBuffer(text.getText());
            date.replace(e.start, e.start + length, newText);
            calendar.set(Calendar.YEAR, 1901);
            calendar.set(Calendar.MONTH, Calendar.JANUARY);
            calendar.set(Calendar.DATE, 1);
            String yyyy = date.substring(0, 4);
            if (yyyy.indexOf('Y') == -1) {
                int year = Integer.parseInt(yyyy);
                calendar.set(Calendar.YEAR, year);
            }
            String mm = date.substring(5, 7);
            if (mm.indexOf('M') == -1) {
                int month = Integer.parseInt(mm) - 1;
                int maxMonth = calendar.getActualMaximum(Calendar.MONTH);
                if (0 > month || month > maxMonth)
                    return;
                calendar.set(Calendar.MONTH, month);
            }
            String dd = date.substring(8, 10);
            if (dd.indexOf('D') == -1) {
                int day = Integer.parseInt(dd);
                int maxDay = calendar.getActualMaximum(Calendar.DATE);
                if (1 > day || day > maxDay)
                    return;
                calendar.set(Calendar.DATE, day);
            } else {
                if (calendar.get(Calendar.MONTH) == Calendar.FEBRUARY) {
                    char firstChar = date.charAt(8);
                    if (firstChar != 'D' && '2' < firstChar)
                        return;
                }
            }
            text.setSelection(e.start, e.start + length);
            ignore = true;
            text.insert(newText);
            ignore = false;
        }
    });
    shell.pack();
    shell.open();
    while (!shell.isDisposed()) {
        if (!display.readAndDispatch())
            display.sleep();
    }
    display.dispose();
}

From source file:UnicodeChars.java

public static void main(String[] argv) {
    //+//from   www.  j  a va  2s. c o m
    StringBuffer b = new StringBuffer();
    for (char c = 'a'; c < 'd'; c++) {
        b.append(c);
    }
    b.append('\u00a5'); // Japanese Yen symbol
    b.append('\u01FC'); // Roman AE with acute accent
    b.append('\u0391'); // GREEK Capital Alpha
    b.append('\u03A9'); // GREEK Capital Omega

    for (int i = 0; i < b.length(); i++) {
        System.out.println("Character #" + i + " is " + b.charAt(i));
    }
    System.out.println("Accumulated characters are " + b);
    //-
}

From source file:com.interacciones.mxcashmarketdata.driver.util.AppropriateFormat.java

public static void main(String[] args) throws Throwable {
    init(args);//from   w w  w  .java2 s .  co m

    long time = System.currentTimeMillis();
    //for (;;) {
    try {
        //read
        file = new File(source);
        is = new FileInputStream(file);
        isr = new InputStreamReader(is);
        br = new BufferedReader(isr);
        //write
        filewrite = new File(destination);
        fos = new FileOutputStream(filewrite);
        bos = new BufferedOutputStream(fos);

        int data = 0;
        int count = 0;

        StringBuffer message = new StringBuffer();
        while (data != -1) {
            data = br.read();
            message.append((char) data);
            count++;
            if (data == 10) {
                transform(message);
                count = 0;
                message.delete(INIT_ASCII, message.length());
            }
        }
    } catch (Exception e) {
        LOGGER.error("Warning " + e.getMessage());
        e.printStackTrace();
    } finally {
        close();
    }
    //}
    time = System.currentTimeMillis() - time;
    LOGGER.info("Time " + time);
}

From source file:discovery.compression.kdd2011.ratio.RatioCompressionReport.java

public static void main(String[] args) throws GraphReadingException, IOException, java.text.ParseException {
    opts.addOption("r", true, "Goal compression ratio");

    //      opts.addOption( "a",
    //       true,
    //       "Algorithm used for compression. The default and only currently available option is \"greedy\"");
    //opts.addOption("cost-output",true,"Output file for costs, default is costs.txt");
    //opts.addOption("cost-format",true,"Output format for ");

    opts.addOption("ctype", true, "Connectivity type: global or local, default is global.");
    opts.addOption("connectivity", false,
            "enables output for connectivity. Connectivity info will be written to connectivity.txt");
    opts.addOption("output_bmg", true, "Write bmg file with groups to given file.");
    opts.addOption("algorithm", true, "Algorithm to use, one of: greedy random1 random2 bruteforce slowgreedy");
    opts.addOption("hop2", false, "Only try to merge nodes that have common neighbors");
    opts.addOption("kmedoids", false, "Enables output for kmedoids clustering");
    opts.addOption("kmedoids_k", true, "Number of clusters to be used in kmedoids. Default is 3");
    opts.addOption("kmedoids_output", true,
            "Output file for kmedoid clusters. Default is clusters.txt. This file will be overwritten.");
    opts.addOption("norefresh", false,
            "Use old style merging: all connectivities are not refreshed when merging");
    opts.addOption("edge_attribute", true, "Attribute from bmgraph used as edge weight");
    opts.addOption("only_times", false, "Only write times.txt");
    //opts.addOption("no_metrics",false,"Exit after compression, don't calculate any metrics or produce output bmg for the compression.");
    CommandLineParser parser = new PosixParser();
    CommandLine cmd = null;//  w  ww.  j  a  va2s .c om

    try {
        cmd = parser.parse(opts, args);
    } catch (ParseException e) {
        e.printStackTrace();
        System.exit(0);
    }

    boolean connectivity = false;
    double ratio = 0;

    boolean hop2 = cmd.hasOption("hop2");

    RatioCompression compression = new GreedyRatioCompression(hop2);

    if (cmd.hasOption("connectivity"))
        connectivity = true;

    ConnectivityType ctype = ConnectivityType.GLOBAL;
    CompressionMergeModel mergeModel = new PathAverageMergeModel();
    if (cmd.hasOption("ctype")) {
        String ctypeStr = cmd.getOptionValue("ctype");
        if (ctypeStr.equals("local")) {
            ctype = ConnectivityType.LOCAL;
            mergeModel = new EdgeAverageMergeModel();
        } else if (ctypeStr.equals("global")) {
            ctype = ConnectivityType.GLOBAL;
            mergeModel = new PathAverageMergeModel();
        } else {
            System.out.println(PROGRAM_NAME + ": unknown connectivity type " + ctypeStr);
            printHelp();
        }
    }

    if (cmd.hasOption("norefresh"))
        mergeModel = new PathAverageMergeModelNorefresh();
    if (cmd.hasOption("algorithm")) {
        String alg = cmd.getOptionValue("algorithm");
        if (alg.equals("greedy")) {
            compression = new GreedyRatioCompression(hop2);
        } else if (alg.equals("random1")) {
            compression = new RandomRatioCompression(hop2);
        } else if (alg.equals("random2")) {
            compression = new SmartRandomRatioCompression(hop2);
        } else if (alg.equals("bruteforce")) {
            compression = new BruteForceCompression(hop2, ctype == ConnectivityType.LOCAL);
        } else if (alg.equals("slowgreedy")) {
            compression = new SlowGreedyRatioCompression(hop2);
        } else {
            System.out.println("algorithm must be one of: greedy random1 random2 bruteforce slowgreedy");
            printHelp();
        }
    }

    compression.setMergeModel(mergeModel);

    if (cmd.hasOption("r")) {
        ratio = Double.parseDouble(cmd.getOptionValue("r"));
    } else {
        System.out.println(PROGRAM_NAME + ": compression ratio not defined");
        printHelp();
    }

    if (cmd.hasOption("help")) {
        printHelp();
    }

    String infile = null;
    if (cmd.getArgs().length != 0) {
        infile = cmd.getArgs()[0];
    } else {
        printHelp();
    }

    boolean kmedoids = false;
    int kmedoidsK = 3;
    String kmedoidsOutput = "clusters.txt";
    if (cmd.hasOption("kmedoids"))
        kmedoids = true;
    if (cmd.hasOption("kmedoids_k"))
        kmedoidsK = Integer.parseInt(cmd.getOptionValue("kmedoids_k"));
    if (cmd.hasOption("kmedoids_output"))
        kmedoidsOutput = cmd.getOptionValue("kmedoids_output");

    String edgeAttrib = "goodness";
    if (cmd.hasOption("edge_attribute"))
        edgeAttrib = cmd.getOptionValue("edge_attribute");

    // This program should directly use bmgraph-java to read and
    // DefaultGraph should have a constructor that takes a BMGraph as an
    // argument.

    //VisualGraph vg = new VisualGraph(infile, edgeAttrib, false);
    //System.out.println("vg read");
    //SimpleVisualGraph origSG = new SimpleVisualGraph(vg);
    BMGraph bmg = BMGraphUtils.readBMGraph(infile);

    int origN = bmg.getNodes().size();

    //for(int i=0;i<origN;i++)
    //System.out.println(i+"="+origSG.getVisualNode(i));
    System.out.println("bmgraph read");

    BMNode[] i2n = new BMNode[origN];
    HashMap<BMNode, Integer> n2i = new HashMap<BMNode, Integer>();
    {
        int pi = 0;
        for (BMNode nod : bmg.getNodes()) {
            n2i.put(nod, pi);
            i2n[pi++] = nod;
        }
    }

    DefaultGraph dg = new DefaultGraph();
    for (BMEdge e : bmg.getEdges()) {
        dg.addEdge(n2i.get(e.getSource()), n2i.get(e.getTarget()), Double.parseDouble(e.get(edgeAttrib)));
    }

    DefaultGraph origDG = dg.copy();

    System.out.println("inputs read");
    RatioCompression nopCompressor = new RatioCompression.DefaultRatioCompression();
    ResultGraph nopResult = nopCompressor.compressGraph(dg, 1);

    long start = System.currentTimeMillis();
    ResultGraph result = compression.compressGraph(dg, ratio);
    long timeSpent = System.currentTimeMillis() - start;
    double seconds = timeSpent * 0.001;

    BufferedWriter timesWriter = new BufferedWriter(new FileWriter("times.txt", true));
    timesWriter.append("" + seconds + "\n");
    timesWriter.close();

    if (cmd.hasOption("only_times")) {
        System.out.println("Compression done, exiting.");
        System.exit(0);
    }

    BufferedWriter costsWriter = new BufferedWriter(new FileWriter("costs.txt", true));
    costsWriter.append("" + nopResult.getCompressorCosts() + " " + result.getCompressorCosts() + "\n");
    costsWriter.close();

    double[][] origProb;
    double[][] compProb;
    int[] group = new int[origN];

    for (int i = 0; i < result.partition.size(); i++)
        for (int x : result.partition.get(i))
            group[x] = i;

    if (ctype == ConnectivityType.LOCAL) {
        origProb = new double[origN][origN];
        compProb = new double[origN][origN];
        DefaultGraph g = result.uncompressedGraph();
        for (int i = 0; i < origN; i++) {
            for (int j = 0; j < origN; j++) {
                origProb[i][j] = dg.getEdgeWeight(i, j);
                compProb[i][j] = g.getEdgeWeight(i, j);
            }
        }
        System.out.println("Writing edge-dissimilarity");
    } else {

        origProb = ProbDijkstra.getProbMatrix(origDG);

        compProb = new double[origN][origN];

        System.out.println("nodeCount = " + result.graph.getNodeCount());
        double[][] ccProb = ProbDijkstra.getProbMatrix(result.graph);
        System.out.println("ccProb.length = " + ccProb.length);

        System.out.println("ccProb[0].length = " + ccProb[0].length);

        for (int i = 0; i < origN; i++) {
            for (int j = 0; j < origN; j++) {
                if (group[i] == group[j])
                    compProb[i][j] = result.graph.getEdgeWeight(group[i], group[j]);
                else {
                    int gj = group[j];
                    int gi = group[i];
                    compProb[i][j] = ccProb[group[i]][group[j]];
                }
            }
        }

        System.out.println("Writing best-path-dissimilarity");
        //compProb = ProbDijkstra.getProbMatrix(result.uncompressedGraph());

    }

    {
        BufferedWriter connWr = null;//

        if (connectivity) {
            connWr = new BufferedWriter(new FileWriter("connectivity.txt", true));
        }
        double totalDiff = 0;

        for (int i = 0; i < origN; i++) {
            for (int j = i + 1; j < origN; j++) {

                double diff = Math.abs(origProb[i][j] - compProb[i][j]);
                //VisualNode ni = origSG.getVisualNode(i);
                //VisualNode nj = origSG.getVisualNode(j);
                BMNode ni = i2n[i];
                BMNode nj = i2n[j];
                if (connectivity)
                    connWr.append(ni + "\t" + nj + "\t" + origProb[i][j] + "\t" + compProb[i][j] + "\t" + diff
                            + "\n");
                totalDiff += diff * diff;
            }
        }

        if (connectivity) {
            connWr.append("\n");
            connWr.close();
        }

        totalDiff = Math.sqrt(totalDiff);
        BufferedWriter dissWr = new BufferedWriter(new FileWriter("dissimilarity.txt", true));
        dissWr.append("" + totalDiff + "\n");
        dissWr.close();
    }

    if (cmd.hasOption("output_bmg")) {
        BMGraph outgraph = new BMGraph();

        String outputfile = cmd.getOptionValue("output_bmg");
        HashMap<Integer, BMNode> nodes = new HashMap<Integer, BMNode>();

        for (int i = 0; i < result.partition.size(); i++) {
            ArrayList<Integer> g = result.partition.get(i);
            if (g.size() == 0)
                continue;
            BMNode node = new BMNode("Supernode_" + i);
            HashMap<String, String> attributes = new HashMap<String, String>();
            StringBuffer contents = new StringBuffer();
            for (int x : g)
                contents.append(i2n[x] + ",");
            contents.delete(contents.length() - 1, contents.length());

            attributes.put("nodes", contents.toString());
            attributes.put("self-edge", "" + result.graph.getEdgeWeight(i, i));
            node.setAttributes(attributes);
            nodes.put(i, node);
            outgraph.ensureHasNode(node);
        }

        for (int i = 0; i < result.partition.size(); i++) {
            if (result.partition.get(i).size() == 0)
                continue;
            for (int x : result.graph.getNeighbors(i)) {
                if (x < i)
                    continue;
                BMNode from = nodes.get(i);
                BMNode to = nodes.get(x);
                if (from == null || to == null) {
                    System.out.println(from + "->" + to);
                    System.out.println(i + "->" + x);
                    System.out.println("");
                }
                BMEdge e = new BMEdge(nodes.get(i), nodes.get(x), "notype");

                e.setAttributes(new HashMap<String, String>());
                e.put("goodness", "" + result.graph.getEdgeWeight(i, x));
                outgraph.ensureHasEdge(e);
            }
        }
        BMGraphUtils.writeBMGraph(outgraph, outputfile);
    }

    // k medoids!
    if (kmedoids) {
        //KMedoidsResult clustersOrig=KMedoids.runKMedoids(origProb,kmedoidsK);

        if (ctype == ConnectivityType.LOCAL) {
            compProb = ProbDijkstra.getProbMatrix(result.uncompressedGraph());
        }

        //KMedoidsResult compClusters = KMedoids.runKMedoids(ProbDijkstra.getProbMatrix(result.graph),kmedoidsK);
        KMedoidsResult clustersComp = KMedoids.runKMedoids(compProb, kmedoidsK);

        BufferedWriter bw = new BufferedWriter(new FileWriter(kmedoidsOutput));

        for (int i = 0; i < origN; i++) {
            int g = group[i];
            //bw.append(origSG.getVisualNode(i).getBMNode()+" "+compClusters.clusters[g]+"\n");
            bw.append(i2n[i] + " " + clustersComp.clusters[i] + "\n");
        }
        bw.close();
    }

    System.exit(0);
}

From source file:com.zigabyte.stock.stratplot.StrategyPlotter.java

/** Starts a StrategyPlotter.
 *  @param parameters//  www.j  a va2 s .  co m
 *  <pre>
 *  Optional Parameters and default values:
 *   -initialCash $10,000.00
 *   -perTradeFee $1.00
 *   -perShareTradeCommission $0.02
 *   -strategy com.zigabyte.stock.strategy.SundayPeaks(0.2,0.08)
 *   -metastock (default path: current directory)
 *   -serialized (default path: current directory)
 *   -serializedgz (default path: current directory)
 *  Values may need to be quoted '$1' or 'pkg.MyStrategy(0.1)'.
 *  Use only one -metastock, -serialized, or -serializedgz to specify data.
 *  </pre>
 **/
public static void main(String... parameters) {
    double initialCash = DEFAULT_INITIAL_CASH;
    double initialPerTradeFee = DEFAULT_PER_TRADE_FEE;
    double initialPerShareTradeCommission = DEFAULT_PER_SHARE_TRADE_COMMISSION;
    String initialStrategy = DEFAULT_STRATEGY;
    String initialDataFormat = DEFAULT_DATA_FORMAT;
    String initialDataPath = DEFAULT_DATA_PATH;

    // parse parameters
    int parameterIndex = 0;
    try {
        for (; parameterIndex < parameters.length; parameterIndex++) {
            String parameter = parameters[parameterIndex];
            if ("-initialCash".equalsIgnoreCase(parameter) || "-perTradeFee".equalsIgnoreCase(parameter)
                    || "-perShareTradeCommission".equalsIgnoreCase(parameter)) {
                double value = DOLLAR_FORMAT.parse(parameters[++parameterIndex]).doubleValue();
                if ("-initialCash".equalsIgnoreCase(parameter)) {
                    initialCash = value;
                } else if ("-perTradeFee".equalsIgnoreCase(parameter)) {
                    initialPerTradeFee = value;
                } else if ("-perShareTradeCommission".equalsIgnoreCase(parameter)) {
                    initialPerShareTradeCommission = value;
                } else
                    assert false;
            } else if ("-strategy".equalsIgnoreCase(parameter) || "-metastock".equalsIgnoreCase(parameter)
                    || "-serialized".equalsIgnoreCase(parameter)
                    || "-serializedgz".equalsIgnoreCase(parameter)) {
                StringBuffer buf = new StringBuffer();
                String part;
                while (++parameterIndex < parameters.length
                        && !(part = parameters[parameterIndex]).startsWith("-")) {
                    if (buf.length() > 0)
                        buf.append(' ');
                    buf.append(part);
                }
                --parameterIndex;
                String value = buf.toString();
                if ("-strategy".equalsIgnoreCase(parameter)) {
                    initialStrategy = value;
                } else if ("-metastock".equalsIgnoreCase(parameter)) {
                    initialDataPath = value;
                    initialDataFormat = "Metastock";
                } else if ("-serialized".equalsIgnoreCase(parameter)) {
                    initialDataPath = value;
                    initialDataFormat = "Serialized";
                } else if ("-serializedgz".equalsIgnoreCase(parameter)) {
                    initialDataPath = value;
                    initialDataFormat = "SerializedGZ";
                } else
                    assert false;
            } else if ("-help".equalsIgnoreCase(parameter)) {
                parameterExit(0);
            } else
                throw new IllegalArgumentException(parameter);
        }
    } catch (Exception e) {
        System.err.println(e);
        int indent = 0;
        for (int i = 0; i < parameters.length; i++) {
            String parameter = parameters[i];
            if (i < parameterIndex)
                indent += parameter.length() + 1;
            System.err.print(parameter);
            System.err.print(' ');
        }
        System.err.println();
        for (int i = 0; i < indent; i++)
            System.err.print('_');
        System.err.println('^');
        parameterExit(-1);
    }

    // set up plotter
    StrategyPlotter plotter = new StrategyPlotter(initialCash, initialPerTradeFee,
            initialPerShareTradeCommission, initialStrategy, initialDataFormat, initialDataPath);
    plotter.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    plotter.setSize(1024, 768);
    plotter.setLocationRelativeTo(null); // center on screen
    plotter.setVisible(true);
}

From source file:TextVerifyInputRegularExpression.java

public static void main(String[] args) {

    Display display = new Display();
    Shell shell = new Shell(display);
    shell.setLayout(new GridLayout());
    final Text text = new Text(shell, SWT.BORDER);
    Font font = new Font(display, "Courier New", 10, SWT.NONE); //$NON-NLS-1$
    text.setFont(font);/*from w ww .j av a 2 s  . c  o  m*/
    text.setText(template);
    text.addListener(SWT.Verify, new Listener() {
        // create the pattern for verification
        Pattern pattern = Pattern.compile(REGEX);

        // ignore event when caused by inserting text inside event handler
        boolean ignore;

        public void handleEvent(Event e) {
            if (ignore)
                return;
            e.doit = false;
            if (e.start > 13 || e.end > 14)
                return;
            StringBuffer buffer = new StringBuffer(e.text);

            // handle backspace
            if (e.character == '\b') {
                for (int i = e.start; i < e.end; i++) {
                    // skip over separators
                    switch (i) {
                    case 0:
                        if (e.start + 1 == e.end) {
                            return;
                        } else {
                            buffer.append('(');
                        }
                        break;
                    case 4:
                        if (e.start + 1 == e.end) {
                            buffer.append(new char[] { '#', ')' });
                            e.start--;
                        } else {
                            buffer.append(')');
                        }
                        break;
                    case 8:
                        if (e.start + 1 == e.end) {
                            buffer.append(new char[] { '#', '-' });
                            e.start--;
                        } else {
                            buffer.append('-');
                        }
                        break;
                    default:
                        buffer.append('#');
                    }
                }
                text.setSelection(e.start, e.start + buffer.length());
                ignore = true;
                text.insert(buffer.toString());
                ignore = false;
                // move cursor backwards over separators
                if (e.start == 5 || e.start == 9)
                    e.start--;
                text.setSelection(e.start, e.start);
                return;
            }

            StringBuffer newText = new StringBuffer(defaultText);
            char[] chars = e.text.toCharArray();
            int index = e.start - 1;
            for (int i = 0; i < e.text.length(); i++) {
                index++;
                switch (index) {
                case 0:
                    if (chars[i] == '(')
                        continue;
                    index++;
                    break;
                case 4:
                    if (chars[i] == ')')
                        continue;
                    index++;
                    break;
                case 8:
                    if (chars[i] == '-')
                        continue;
                    index++;
                    break;
                }
                if (index >= newText.length())
                    return;
                newText.setCharAt(index, chars[i]);
            }
            // if text is selected, do not paste beyond range of selection
            if (e.start < e.end && index + 1 != e.end)
                return;
            Matcher matcher = pattern.matcher(newText);
            if (matcher.lookingAt()) {
                text.setSelection(e.start, index + 1);
                ignore = true;
                text.insert(newText.substring(e.start, index + 1));
                ignore = false;
            }
        }
    });

    shell.pack();
    shell.open();
    while (!shell.isDisposed()) {
        if (!display.readAndDispatch())
            display.sleep();
    }
    font.dispose();
    display.dispose();
}