我想知道最简单的方法是将整数转换为等效数量的空格。打印二叉搜索树时,我需要它作为节点之间的空间。这个我试过了
int position = printNode.getPosition();
String formatter = "%1"+position+"s%2$s\n";
System.out.format(formatter, "", node.element);
但与 position 的 int 值相比,我得到的空间几乎是 3 倍。我也不太确定我是否正确地格式化了字符串。 任何建议都会很棒! 如果它更清楚,说 position = 6;我想在我的节点元素之前打印 6 个空格。
最佳答案
我想你的意思是这样的:
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)
关于java - 将整数转换为等效数量的空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2635076/