This method creates small status bars in ASCII art for printing in the console or in log files. - Java Language Basics

Java examples for Language Basics:Console

Description

This method creates small status bars in ASCII art for printing in the console or in log files.

Demo Code


//package com.java2s;

public class Main {
    public static void main(String[] argv) throws Exception {
        int length = 2;
        double d = 2.45678;
        boolean showPercentage = true;
        System.out.println(createPercentageBar(length, d, showPercentage));
    }//from  w  ww  .  j  a va 2s .  co m

    /**
     * This method creates small status bars in ASCII art for printing in the
     * console or in log files. The status bar looks like "[********.........]"
     * without shown percentage or "[*******........] ( 45%)" with percentage
     * shown.
     * 
     * @param length
     *            is the total length of the status bar. In this length the
     *            brackets are included. The percentage number is extra length.
     * @param d
     *            is the percentage to show.
     * @param showPercentage
     *            defines whether the percentage value is to be shown.
     * @return A String is returned containing the ASCII art representation of
     *         the string
     */
    public static String createPercentageBar(int length, double d,
            boolean showPercentage) {
        StringBuffer buffer = new StringBuffer("[");
        int starNum = (int) Math.round(d * (length - 2));
        for (int dummy = 1; dummy <= length - 2; dummy++) {
            if (dummy <= starNum) {
                buffer.append('*');
            } else {
                buffer.append('.');
            }
        }
        buffer.append(']');
        if (showPercentage) {
            buffer.append(" (");
            StringBuffer num = new StringBuffer(String.valueOf((int) Math
                    .round(d * 100.0)));
            while (num.length() < 3) {
                num.insert(0, ' ');
            }
            buffer.append(num);
            buffer.append("%)");
        }
        return buffer.toString();
    }
}

Related Tutorials