0

How would I format a set amount of spaces for results to look like these? Trying to get the exact spacing types between the Grade, Count and % outputs. Count column should match up with the letter t. The one I'm especially confused about is % due to the indentation differences depending on the number; e.g. if it is 100.00 the 1 should align with %, multiple of 10 i.e. 10-99.00 should be 1 space after %, and 0.00 should be 2 spaces after %.

Thanks in advance!

*Grade Count %

*__________________________

*F 0 0.00

*P 1 20.00

*C 2 40.00

*D 0 0.00

*HD 2 40.00

1

1 Answer 1

2

What you're looking for is called "fixed column width" formatting. The easiest way to achieve it is to use the printf method. In your case, you'd do something like this:

    System.out.println("Grade Count %");
    System.out.println("----- ----- ------");
    for (Grade g : grades) {
        System.out.printf("%-5s %5d %6.2f%n", 
            g.getGrade(), g.getCount(), g.getPercent());
    }

The first argument to printf is a format string that includes both fixed text (here just some spaces) and format specifiers that start with a % and end with a letter; the remaining arguments are the data to be formatted. Here's a brief breakdown of the format string in this example:

  • %-5s matches with the g.getGrade() argument; the 5 means a fixed field width of 5 columns, the - means left-justify, the s means we're formatting a String argument

  • %5d matches with the g.getCount() argument; the d means we're formatting a decimal integer (int, long, or BigDecimal) number, 5 is the field width, and the lack of a - implies right-justification;

  • %6.2f matches with the g.getPercent() argument; the f means we're formatting a floating-point (float, double or BigDecimal) number, 6 is the overall field width, .2 means there will be 2 digits after the decimal point, and no - means to right-justify.

For a more complete discussion, read format strings.

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

1 Comment

My bad! %-6.2f should have been %6.2f. (without the -) to right-align the percents.

Your Answer

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