I was wondering what the easiest way is to convert an integer to the equivalent number of blank spaces. I need it for the spaces between nodes when printing a binary search tree. I tried this
int position = printNode.getPosition();
String formatter = "%1"+position+"s%2$s\n";
System.out.format(formatter, "", node.element);
But I am getting almost 3 times as many spaces compared to the int value of position. I'm not really sure if I am formatting the string right either. Any suggestions would be great! If it makes it clearer, say position = 6; I want 6 blank spaces printed before my node element.
I think you meant something like:
int n = 6;
String s = String.format("%1$"+n+"s", "");
System.out.format("[%13s]%n", ""); // prints "[ ]" (13 spaces)
System.out.format("[%1$3s]%n", ""); // prints "[ ]" (3 spaces)
This is an easy, but rubbish, way:
int count = 20;
String spaces = String.format("%"+count+"s", "");
or filled in
String spaces = String.format("%20s", "");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With