user2840682
user2840682

Reputation: 381

Why won't one of the String constants format in the toString method?

Every other variable will format accordingly but the BANK_NAME constants will just not adhere to any of the formatting. Any reason why? Solutions?

 /**
 * Returns information about the CD account
 * @return  formatted string for CD account information
 */
public String toString()
{
    return String.format("Investment Type: %.13s\n" +
                         "Held By: %.34s\n" + //THIS ONE WILL NOT FORMAT
                         "%30s\n" +
                         "Balance: %15.2f\n" +
                         "Annual Int. Rate: $%4.2f\n",
                         ACCOUNT_TYPE,BANK_NAME,BANK_ADDRESS,getBalance(),calcInterest());
}

OUTPUT SAMPLE:

       Investment Type:  CD 1 Yr
       Held By: First Rochester Bank
                         Rochester, NY
       Balance:          5000.00
       Annual Int. Rate: $177.83

Upvotes: 0

Views: 214

Answers (1)

Ted Hopp
Ted Hopp

Reputation: 234847

If you want all the data to align on the left of a specific column in the output, you should do it with explicit padding rather than with field widths. For one thing, if you get the alignment correct using your method for one name, it will be wrong for another name of different length. Try this instead:

public String toString()
{
    return String.format("Investment Type:  %.13s%n" +
                         "Held By:          %s%n" +
                         "                  %s%n" +
                         "Balance:          %.2f%n" +
                         "Annual Int. Rate: $%4.2f%n",
                         ACCOUNT_TYPE,
                         BANK_NAME,
                         BANK_ADDRESS,
                         getBalance(),
                         calcInterest()
    );
}

Note that I changed the newline escape sequences with a newline format specifier. It's generally better to do that for cross-platform compatibility.

Upvotes: 2

Related Questions