Question

I have information from a text file that I have read in through 3 parallel arrays. There's one for names, id numbers, and gpa. However because the name lengths vary the id numbers and gpa are all shifted differently. Is there a way to align all the id numbers so they begin on the same part of the line and the same for the gpa's despite different name lengths? I used a for loop for all of it and my code looks like this:

    {
        int lineLength;
        lineLength = lineFinder(names);

        System.out.printf("NAME                 ID             GPA\n");
        System.out.println();
        for(int i = 0; i < lineLength; i++)
        {
            System.out.printf("%s %14d %14.2f", names[i] , id[i], gpa[i]);
            System.out.println();

        }

    }

Any suggestions would be appreciated :)

Was it helpful?

Solution

Take a look at the JavaDocs for the Formatter. The printf method is ultimately using that class to format the output for you.

In your case, it sounds like you want to left-justify the ID values. By default, as you've probably seen, everything is always right-justified, and as Ooga said in the comments, a negative number in the formatting will left-justify.

However I believe part of the problem is that you're not specifying the length of the name field. It'll shrink or expand based on the length of the string provided, which I'm guessing is why you're saying your output looks all over the place. I would specify a length in the format (something reasonable, such as 30 perhaps).

So in your case, I think you will want to do something like this:

{
    int lineLength;
    lineLength = lineFinder(names);

    System.out.printf("%30s %14s %14s", "NAME", "ID", "GPA");
    System.out.println();
    for(int i = 0; i < lineLength; i++)
    {
        System.out.printf("%30s %-14d %14.2f", names[i] , id[i], gpa[i]);
        System.out.println();

    }

}

Also note I've added similar formatting to your field headers that roughly match the lengths of the data. That way everything appears consistently and tabular. You can of course play with the values as you need.

Hope that helps.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top