我想格式化表格,如// !!! Extremely important !!!所示。但我有问题右对齐整数。从图中可以看出,顶部的前四行,整数是右对齐的。有没有办法通过System.out.printf()
或String.format()
对齐整数?到目前为止我试图做的就像它;但它不一样。整数左对齐。
String line = String.format("\n\nREGISTERS:\n");
line += String.format("%-21s %+05d\n%-21s %02d\n%-21s %+05d\n%-21s %02d\n%-21s %02d\n\n","accumulator",accum,
"instructionCounter",instructionCounter,"instructionRegister",instructionRegister,"operationCode",operationCode,"operand",operand);
line += (String.format("MEMORY:\n"));
line += (String.format("%5d%5d%5d%5d%5d%5d%5d%5d%5d%5d\n",0,1,2,3,4,5,6,7,8,9));
for(int i = 0; i < memory.length; i += 10){
line += String.format("%2d ", i);
for(int j = i; j < i+9; j++){
line += String.format("%+05d ", memory[j]);
}
line += "\n";
}
答案 0 :(得分:1)
一种方法是将整数格式化为字符串,方法是将String.format()
传递给自己,如下所示:
String.format("'%5s'", String.format("%02d", instructionCounter))
所以代码中的那一行就变成了这样:
line += String.format("%-21s%+05d\n%-21s%6s%-21s%+05d\n%-21s%6s%-21s%6s",
"accumulator",accum,
"instructionCounter",String.format("%02d\n", instructionCounter),
"instructionRegister",instructionRegister,
"operationCode",String.format("%02d\n", operationCode),
"operand",String.format("%02d\n", operand) );
生成输出:
REGISTERS:
accumulator +0000
instructionCounter 00
instructionRegister +0000
operationCode 00
operand 00
希望这有帮助!