gpt4 book ai didi

java - 右对齐整数 (Java)

转载 作者:行者123 更新时间:2023-11-30 07:17:30 25 4
gpt4 key购买 nike

我想格式化表格,如 here 所示。但我在右对齐整数时遇到问题。如图所示,顶部的前四行,整数右对齐。有没有办法通过 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";
}

最佳答案

一种方法可能是通过将 String.format() 传递给自身来将整数格式化为字符串,如下所示:String.format("'%5s'", String.format("%02d", instructionsCounter))
所以你的代码中的那一行就变成了这样:

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

希望这有帮助!

关于java - 右对齐整数 (Java),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38129173/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com