2016-06-30 57 views
1

我想格式化一个表,如here所示。但我有问题,正确对齐整数。从图中可以看出,顶部的前四行,整数右对齐。有没有什么办法通过System.out.printf()String.format()这样对齐整数?我试图做的很像它。但它不一样。整数左对齐。右对齐整数(Java)

 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

可能使用[使用Javas System.out.format对齐整数值](http://stackoverflow.com/questions/8215282/using-javas-system-out-format-to-align-integer-values) – shmosel

+0

@shmosel在发布之前,我尝试了所有在这个问题中提供的解决方案,他们都没有工作。发布后我再次尝试过。尤其是被接受的答案。 – fafinu

回答

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 

希望这有助于!

+0

它会使它更简洁,但并不能解决问题。谢谢。 – fafinu

+0

此输出格式如表所示。如果这将整数输出为右对齐,但不能解决问题,那么原始问题是什么? – davedwards

+0

我的不好,它确实。我正在做其他事情,并搞砸了。 – fafinu