3

Let's say I have a couple variable and I want to format them so they're all aligned, but the variables are different lengths. For example:

String a = "abcdef";
String b = "abcdefhijk";

And I also have a price.

double price = 4.56;

How would I be able to format it so no matter how long the String is, they are aligned either way?

System.out.format("%5s %10.2f", a, price);
System.out.format("%5s %10.2f", b, price);

For example, the code above would output something like this:

abcdef       4.56
abcdefhijk       4.56

But I want it to output something like this:

abcdef      4.56
abcdefhijk  4.56

How would I go about doing so? Thanks in advance.

5 Answers 5

8

Use fixed size format:

Using format strings with fixed size permits to print the strings in a table-like appearance with fixed size columns:

String rowsStrings[] = new String[] {"1", 
                                     "1234", 
                                     "1234567", 
                                     "123456789"};

String column1Format = "%-3.3s";  // fixed size 3 characters, left aligned
String column2Format = "%-8.8s";  // fixed size 8 characters, left aligned
String column3Format = "%6.6s";   // fixed size 6 characters, right aligned
String formatInfo = column1Format + " " + column2Format + " " + column3Format;

for(int i = 0; i < rowsStrings.length; i++) {
    System.out.format(formatInfo, rowsStrings[i], rowsStrings[i], rowsStrings[i]);
    System.out.println();
} 

Output:

1   1             1
123 1234       1234
123 1234567  123456
123 12345678 123456

In your case you could find the maximum length of the strings you want to display and use that to create the appropriate format information, for example:

// find the max length
int maxLength = Math.max(a.length(), b.length());

// add some space to separate the columns
int column1Length = maxLength + 2;

// compose the fixed size format for the first column
String column1Format = "%-" + column1Length + "." + column1Length + "s";

// second column format
String column2Format = "%10.2f";

// compose the complete format information
String formatInfo = column1Format + " " + column2Format;

System.out.format(formatInfo, a, price);
System.out.println();
System.out.format(formatInfo, b, price);
Sign up to request clarification or add additional context in comments.

4 Comments

I think OP is asking when the maximum length of a and b are unknown.
@LorisSecuro Hmm. Interesting. I guess I could do this, only problem is we haven't learned about this in class at all so I'm not sure if I'm allowed to use it. Was looking for a way to do it solely using String.format() but I guess there isn't a way to do it? Thanks.
@blyter my answer is using the same methods you used in your question, it doesn't really add new concepts.
@ElliottFrisch added an example to find and use the maximum length
1

Put negative sign in front of your format specifier so instead of printing 5 spaces to the left of your float value, it adjusts the space on the right until you find the ideal position. It should be fine

Comments

1

You can achieve it as below-

    String a = "abcdef";
    String b = "abcdefhijk";
    double price = 4.56;

    System.out.println(String.format("%-10s %-10.2f", a, price));
    System.out.println(String.format("%-10s %-10.2f", b, price));

output:

   abcdef     4.56      
   abcdefhijk 4.56

Comments

0

You can find the longest String, and then use Apache commons-lang StringUtils to leftPad both of your String(s). Something like,

int len = Math.max(a.length(), b.length()) + 2;
a = StringUtils.leftPad(a, len);
b = StringUtils.leftPad(b, len);

Or, if you can't use StringUtils - you could implement leftPad. First a method to generate String of whitespace. Something like,

private static String genString(int len) {
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < len; i++) {
        sb.append(' ');
    }
    return sb.toString();
}

Then use it to implement leftPad - like,

private static String leftPad(String in, int len) {
    return new StringBuilder(in) //
            .append(genString(len - in.length() - 1)).toString();
}

And, I tested it like,

int len = Math.max(a.length(), b.length()) + 2;
System.out.format("%s %.2f%n", leftPad(a, len), price);
System.out.format("%s %.2f%n", leftPad(b, len), price);

Which outputs (as I think you wanted)

abcdef      4.56
abcdefhijk  4.56

Comments

0
private String addEnoughSpacesInBetween(String firstStr, String secondStr){

    if (!firstStr.isEmpty() && !secondStr.isEmpty()){

        String space = " ";

        int totalAllowed = 55;

        int multiplyFor = totalAllowed - (firstStr.length() + secondStr.length());

        return StringUtils.repeat(space,multiplyFor);
    }
    return null;
}

1 Comment

You should add some explanation.

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.