Displaying/Formatting Output
CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 5 of 5

Thread: Displaying/Formatting Output

  1. #1
    Join Date
    Apr 2009
    Posts
    7

    Displaying/Formatting Output

    Ok so besides the normal system.out.println() what other ways are there to display out specifically in a different layout or format. I have been told that the printf() method would be best for what I want but I figured I would check here. Let me explain a little more of what I am trying to do.

    I am trying to display variable values with different titles similar to a basic chart I guess I would say. Something like this:



    Deposit <---------------> Withdrawal <-------------> Balance
    ---------- <---------------> -------------- <-------------> ----------
    <---------------------------------------------------------->510.25
    <---------------------------> -500.10 <---------------> 10.15
    80.00<-------------------------------------------------->90.15
    <---------------------------->-70.15 <----------------> 20.00
    <---------------------------->-30.00<-----------------> -10.00
    100<----------------------------------------------------->90.00
    -------------------------------------------------------------
    Surcharge = 10.00 Balance = 80.00
    Interest = 0.40 Balance = 80.40



    Now I could get it to print out all sorts of ways just using println like normal but there must be an easier way.

    Also I would have a different variable for each field and would want to display it as the program is reading the input and then displaying the bottom part when it ends.

    Any suggestions?

    Thanks in advance and sorry if I left something out im still new
    Last edited by tbk0de; April 12th, 2009 at 04:58 PM.

  2. #2
    Join Date
    Apr 2009
    Posts
    7

    Re: Displaying/Formatting Output

    Ok it seems I cant get the formatting on this post to even look right, LOL. It wont let me add more than one space in a row so I added "--" to try and fill that space. Basically its supposed to look like rows and columns each line represents one input of information and then the resulting balance and its supposed to be in line with its column title.

  3. #3
    dlorde is offline Elite Member Power Poster
    Join Date
    Aug 1999
    Location
    UK
    Posts
    10,163

    Re: Displaying/Formatting Output

    Quote Originally Posted by tbk0de View Post
    Now I could get it to print out all sorts of ways just using println like normal but there must be an easier way.
    Unless you describe what you think is the easiest way, how do we know whether we can suggest an easier one?

    If you read the printf method API docs, you'll see it can specify a minimum width in each format specifier, which would save you the trouble of calculating the space padding for entries in each column... would that be easier than the ways you had in mind with println?

    There is nothing so useless as doing efficiently that which should not be done at all...
    P. Drucker
    Please use &#91;CODE]...your code here...&#91;/CODE] tags when posting code. If you get an error, please post the full error message and stack trace, if present.

  4. #4
    Join Date
    Apr 2009
    Posts
    7

    Re: Displaying/Formatting Output

    ok this is what I have right now....

    public static void main(String[] args) {

    //create a scanner
    Scanner input = new Scanner(System.in);

    //prompt user for account info
    System.out.println("Please input your checking account information... ");
    System.out.println();

    float balance = 0;
    int end = 1;
    float deposit = 0;
    float withdrawal = 0;
    int surcharge = 0;
    float interest = 0;

    System.out.println(" Deposit Withdrawal Balance ");
    while (end != 0)
    {
    float nextFloat = input.nextFloat();
    if (nextFloat == 0 )
    {
    end = 0;
    }
    if (nextFloat > 0)
    {
    deposit = nextFloat;
    balance = balance + nextFloat;
    System.out.println(" " + deposit + " " + balance);
    }
    if (nextFloat < 0)
    {
    withdrawal = withdrawal + nextFloat;
    if(balance < 0)
    {
    balance = balance - 10;
    surcharge = surcharge + 10;
    }
    balance = balance + nextFloat;
    System.out.println(" "+ withdrawal + " " + balance);
    }

    }

    System.out.println("-----------------------------------------------------");
    System.out.println("Surcharge: " + surcharge + " balance: " + balance);

    interest = (float) (balance * .005);
    balance = interest + balance;
    System.out.println("Interest: " + interest + " balance: " + balance);
    }




    It works well enough and it seems that the printf will do the same thing only it might be shorter to type than me putting in all the spaces, either way doesnt make too much of a difference to me. Is there something that I may be missing or something that I could be doing better or it this just about it? Thanks for the input/response btw dlorde.



    edit---ok how come I cant type multiple spaces in any post? it is altering the code above, again im probably doing something wrong

  5. #5
    dlorde is offline Elite Member Power Poster
    Join Date
    Aug 1999
    Location
    UK
    Posts
    10,163

    Re: Displaying/Formatting Output

    Quote Originally Posted by tbk0de View Post
    It works well enough and it seems that the printf will do the same thing only it might be shorter to type than me putting in all the spaces, either way doesnt make too much of a difference to me. Is there something that I may be missing or something that I could be doing better or it this just about it?
    You could tidy it up by putting the literal spaces into named String constants. You could use the DecimalFormat class to format your amounts with 2 decimals, currency symbol and thousands separators. You could make the decimal points of the money amounts line up so it all looks neat...

    If you want to do all this, break the formatting problem down into simple chunks. You want to print out a number of lines, all formatted the same - so make a printLine method. Each line has 3 items aligned in columns, so give the printLine method 3 parameters of items to put in the columns. You want each column to line up right-aligned, which means adjusting the number of leading spaces according to the length of the item, so make a getColumn method that adds the right amount of spaces to an item for printing. It's not the amount of code that matters when deciding to break a method down into smaller methods, it's the structure of the problem and readability. Look for common patterns & themes, avoid repeating code, and simplify to make life easier, for example:
    Code:
    private static final String SPACES = "                   ";
    private static final String DEP = "Deposit";
    private static final String WD = "Withdrawal";
    private static final String BAL = "Balance";
    
    public static void main(String[] args) {
    
        //create a scanner
        Scanner input = new Scanner(System.in);
    
        //prompt user for account info
        System.out.println("Please input your checking account information... ");
        System.out.println();
    
        float balance = 0;
        int end = 1;
        float deposit = 0;
        float withdrawal = 0;
        int surcharge = 0;
        float interest = 0;
    
        // Create a formatter for the amounts (the \u00A4 is the currency symbol for the locale
        // you could hard code it instead, e.g: "$###,##0.00"
        NumberFormat formatter = new DecimalFormat("\u00A4###,##0.00");
    
        // Print the 3 column headings
        printLine("Deposit", "Withdrawal", "Balance");
    
        while (end != 0) {
            float nextFloat = input.nextFloat();
            if (nextFloat == 0) {
                end = 0;
            }
            if (nextFloat > 0) {
                deposit = nextFloat;
                balance = balance + nextFloat;
    
                // format the values to print
                final String depStr = formatter.format(deposit);
                final String balStr = formatter.format(balance);
    
                // print the line (note empty withdrawal string)
                printLine(depStr, "", balStr);
            }
            if (nextFloat < 0) {
                withdrawal = withdrawal + nextFloat;
                if (balance < 0) {
                    balance = balance - 10;
                    surcharge = surcharge + 10;
                }
                balance = balance + nextFloat;
    
                // format the values to print
                final String wdStr = formatter.format(withdrawal);
                final String balStr = formatter.format(balance);
    
                // print the line (note empty deposit string)
                printLine("", wdStr, balStr);
            }
        }
    
        System.out.println("-----------------------------------------------------");
        System.out.println("Surcharge: " + surcharge + "          balance: " + balance);
    
        interest = (float) (balance * .005);
        balance = interest + balance;
        System.out.println("Interest: " + interest + "          balance: " + balance);
    }
    
    // print 3 column items
    static void printLine(String col1, String col2, String col3) {
        String outString = getColumn(col1) + getColumn(col2) + getColumn(col3);
        System.out.println(outString);
    }
    
    // return a constant-width column string, right aligned
    static String getColumn(String columnText) {
        return SPACES.substring(columnText.length()) + columnText;
    }
    Incidentally, using floating-point types for money is a bad idea unless you want to do a lot of fiddly rounding to avoid errors (floating-point can't represent all integers exactly). It's better to use integral types such as integer, long, or the BigInteger class, and calculate the amounts in the smallest denomination (cents, pence, etc). Then you only need the decimals when it comes to formatting your output.

    ok how come I cant type multiple spaces in any post?
    The forum, like most forums, works with HTML text, so multiple spaces are reduced to one. If you want to keep the formatting and spaces, post your code in CODE tags.

    Programs must be written for people to read, and only incidentally for machines to execute...
    H. Abelson and G. Sussman
    Last edited by dlorde; April 13th, 2009 at 08:15 AM.
    Please use &#91;CODE]...your code here...&#91;/CODE] tags when posting code. If you get an error, please post the full error message and stack trace, if present.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  


Windows Mobile Development Center


Click Here to Expand Forum to Full Width

This is a CodeGuru survey question.


Featured


HTML5 Development Center