Java – converts an integer to an equivalent number of spaces
•
Java
I want to know that the easiest way is to convert an integer to an equivalent number of spaces When printing a binary search tree, I need its spaces between nodes I tried
int position = printNode.getPosition(); String formatter = "%1"+position+"s%2$s\n"; System.out.format(formatter,"",node.element);
But compared with the int value of the position, my space is almost three times I'm not sure if I format the string correctly Any suggestion would be great! If it is clearer, say position = 6; I want to print six spaces before my node element
Solution
I think you mean:
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)
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码