1

I would like the output to display as following.

ID      Name                 Club            Goals
1234    Christiano Ronaldo   Real Madrid     42
321     Rooney               United          32
23122   Angel Di Maria       United          45

This is what I have tried so far, but it's not working:

for (Player p :  players)
{
    System.out.println(p.getID() + "\t" + p.getName() + "\t"
            + p.getClub()  + "\t" + p.getGoals());
    total ++;
}

since \t act like tab, the data under club always get messy. I have all the data in an ArrayList.

1
  • 1
    Just check the length of each field value, and add spaces to complete. Commented Oct 7, 2014 at 15:17

1 Answer 1

4

You need to use System.out.format.

You can control the lengths of fields like this:

System.out.format("%32s%10d%16s", string1, int1, string2);

This pads string1, int1, and string2 to 32, 10, and 16 characters, respectively.

See the Javadocs for java.util.Formatter for more information on the syntax (System.out.format uses a Formatter internally).

Also, FYI, try overriding the ToString() method for the Player class and defining how you want this class to represent itself. This saves from having to have duplicate code and you can just say:

p.ToString()

and it will print out what it is (ID, name, club, goals).

Sign up to request clarification or add additional context in comments.

3 Comments

Whats if you don't know the length of the output?
Just like databases, you need to set a max length to variables. Ex: If a name has 26 characters and you specify 25, you should implement a way to shorten the name to fit the format you define.
Mark as answer if it works please :) I am glad it worked for you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.