Advertisement
Help Keep Boards Alive. Support us by going ad free today. See here: https://subscriptions.boards.ie/.
If we do not hit our goal we will be forced to close the site.

Current status: https://keepboardsalive.com/

Annual subs are best for most impact. If you are still undecided on going Ad Free - you can also donate using the Paypal Donate option. All contribution helps. Thank you.
https://www.boards.ie/group/1878-subscribers-forum

Private Group for paid up members of Boards.ie. Join the club.

Left alignment in java

  • 19-03-2004 01:51PM
    #1
    Registered Users, Registered Users 2 Posts: 488 ✭✭


    could some tell me how to align a print statement like so...(the out put will be a name and number)..

    name number
    ***** ********
    ***** ********
    ***** ********


Comments

  • Registered Users, Registered Users 2 Posts: 21,264 ✭✭✭✭Hobbes


    probably an easier way to do it but something like

    take the left 5 characters of "name" +"xxxxx" (x = space)


  • Closed Accounts Posts: 1,502 ✭✭✭MrPinK


    Getting the substring of name plus a string of spaces is probably the most efficent, but I like
    while(name.length() < COLUMN_SIZE)
       name += " ";
    


  • Registered Users, Registered Users 2 Posts: 68,173 ✭✭✭✭seamus


    The '\t' escape character works in Java to add in tab spaces.....


  • Registered Users, Registered Users 2 Posts: 19,396 ✭✭✭✭Karoma


    \t is probably safest/cleanest. Otherwise, use one of the many libraries that emulate C's printf statement.. (Which appears to be part of 1.5 now!?)


  • Closed Accounts Posts: 1,502 ✭✭✭MrPinK


    Tabs only work properly if the range of lengths fit within the same tab, i.e. all lengths between 0 - 7, 8 - 15, etc.


  • Advertisement
  • Registered Users, Registered Users 2 Posts: 68,173 ✭✭✭✭seamus


    Originally posted by MrPinK
    Tabs only work properly if the range of lengths fit within the same tab, i.e. all lengths between 0 - 7, 8 - 15, etc.
    I'm sure a clever individual could come up with a small method to find the longest name, and then calculate the no. of tab spaces needed to align each number correctly :)


  • Closed Accounts Posts: 1,502 ✭✭✭MrPinK


    True, but a person as clever as that would no doubt hate to have to iterate through a collection twice when once is enough :)


  • Registered Users, Registered Users 2 Posts: 27,518 ✭✭✭✭GreeBo


    but presumably the items are in an array/vector/hashmap so take note of the longest when you stick em in?


  • Registered Users, Registered Users 2 Posts: 4,660 ✭✭✭Gavin


    java.text.Format may be of use.


Advertisement