java - 右对齐整数 (Java)

标签 java formatting

我想格式化表格,如 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/

相关文章:

java - 线程监视器重新启动死线程有什么意义吗?

c++ - 通过 clang-format 实现格式化的好方法是什么?

linq - ReSharper LINQ 扩展方法格式化

java - Eclipse 在哪里存储首选项?

python - 如何在 python 脚本中格式化 postgreSQL 查询以获得更好的可读性?

c - 解析字符串,忽略相对位置中的空格 - sscanf

java - 为什么在 setDropTarget() 之后不再调用 canImport()?

java - 以给定的分贝生成音轨声音

java - SimpleDateFormat 抛出异常

java - 使用另一个线程获取在一个线程中创建的数据