Advertisement
If you have a new account but are having problems posting or verifying your account, please email us on hello@boards.ie for help. Thanks :)
Hello all! Please ensure that you are posting a new thread or question in the appropriate forum. The Feedback forum is overwhelmed with questions that are having to be moved elsewhere. If you need help to verify your account contact hello@boards.ie

Left alignment in java

Options
  • 19-03-2004 1:51pm
    #1
    Registered Users 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 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 Posts: 68,317 ✭✭✭✭seamus


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


  • Registered Users 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 Posts: 68,317 ✭✭✭✭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 Posts: 27,114 ✭✭✭✭GreeBo


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


  • Registered Users Posts: 4,676 ✭✭✭Gavin


    java.text.Format may be of use.


Advertisement