How to print() colums

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Alan G
    New Member
    • Mar 2007
    • 1

    How to print() colums

    I'm grateful for any help here!

    My program is generally quite a simple problem; must read in a list containing names and numbers and print it out like a phonebook in alphabetical order, in order of surname, comma, forename, and a number in a 2nd column. An example of the input is:

    Fred Flintstone 555437
    John Wayne 645373
    Michael Schumacher 0343653
    etc.

    And the output should be:

    Flintstone, Fred
    555437
    Michael, Schumacher
    0343653
    John, Wayne
    645373

    In my program I must create a class called person (strings of forename surname etc). I have an array of type Person (each array slot contains 3 strings [I use the number as a string]).

    Everything works perfectly. The only problem is the printing part. As normal I'm printing the array with a for loop, concatenating the elements in the desired order, eg

    static void printPerson(Per son[] bk, int length)
    {
    for (int y = 0; y < length; y++)
    {
    String num = bk[y].number;
    System.out.prin tln(bk[y].surname + ", " + bk[y].forename + ('\t') + ('\t') + bk[y].number);
    }
    }


    Of course what happens here is that when a name is above a certain length, the number will tab over even further. So it's not a solution. I was recommended to look at using printf(), but not getting the result with it. So anybody have any idea (...quite likely a simple answer!)
  • horace1
    Recognized Expert Top Contributor
    • Nov 2006
    • 1510

    #2
    use system.out.prin tf
    http://java.sun.com/developer/technicalArticl es/Programming/sprintf/

    e.g.
    Code:
        String s1="Fred Flintstone";
        int i1=555437;
        String s2="John Wayne";
        int i2= 645373;
        String s3="Michael Schumacher";
        int i3= 0343653;
        System.out.printf("%25s %10d\n", s1, i1);
        System.out.printf("%25s %10d\n", s2, i2);
        System.out.printf("%25s %10d\n", s3, i3);
    would print
    Code:
              Fred Flintstone     555437
                   John Wayne     645373
           Michael Schumacher     116651

    Comment

    Working...