1

Within a method, I have the following code:

s = s + (items[i] + ":" + numItems[i]+" @ "+prices[i]+" cents each.\n");

Which outputs:

Candy:      5 @ 50 cents each.
Soda:     3 @ 10 cents each.

and so on . . .

Within this line, how do I get the 5, 3, etc . . to line up with each other so that it is:

Candy:      5 @ 50 cents each.
Soda:       3 @ 10 cents each.

This is part of a toString() method, so I can't do it with a System.out.printf

Alexis C.
  • 82,826
  • 18
  • 154
  • 166
  • 1
    See [String.format()](http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#format%28java.lang.String,%20java.lang.Object...%29), works the same as `printf` but returns a String rather outputting it.. – Ray Stojonic Nov 25 '13 at 22:33

4 Answers4

1

String.format() and the Formatter classes can be used.

Following code will output something like this

 /*
 Sample Text    #
     Sample Text#
 */

Code

 public static String padRight(String s, int n) {
    return String.format("%1$-" + n + "s", s);  
 }

 public static String padLeft(String s, int n) {
     return String.format("%1$" + n + "s", s);  
 }

 public static void main(String args[]) throws Exception {
    System.out.println(padRight("Sample Text", 15) + "#");
    System.out.println(padLeft("Sample Text", 15) + "#");
 }

Some more snippet for formatting

 String.format("%5s", "Hi").replace(' ', '*');
 String.format("%-5s", "Bye").replace(' ', '*');
 String.format("%5s", ">5 chars").replace(' ', '*');

output:

 ***Hi
 Bye**
 >5*chars

Apart from this Apache StringUtils API has lot of methods like rightPad, leftPad for doing this. Link

Vallabh Patade
  • 4,570
  • 5
  • 29
  • 40
0

You can use the tab character \t in your toString()

Heres an example:

System.out.println("Candy \t 5");
System.out.println("Soda \t 10");

Candy    5
Soda     10

So in your case

s = s + (items[i] + ": \t" + numItems[i]+" @ "+prices[i]+" cents each.\n");
James Barnett
  • 4,879
  • 3
  • 13
  • 18
0

You can maybe use the \t for inserting a tab.

XD face me
  • 528
  • 1
  • 3
  • 11
0

try this

s = s + (makeFixedLengthString(items[i]) + ":" + numItems[i]+" @ "+prices[i]+" cents each.\n");

public String makeFixedLengthString(String src){
        int len = 15;
        for(int i = len-src.length(); i < len; i++)
            src+=" ";
        return src;
}
subash
  • 3,061
  • 2
  • 14
  • 20