fafinu fafinu - 1 year ago 106
Java Question

Right align integers (Java)

I wanted to format a table as shown in here. But I have problem right-aligning integers. As can be seen in picture, the first four rows at the top, integers are right aligned. Is there any way to align integers via

System.out.printf()
or
String.format()
as such? What I tried to do so far resembles it; but its not the same. Integers are left aligned.

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";
}

Answer Source

One way may be to format the integers as a string by passing a String.format() to itself like this: String.format("'%5s'", String.format("%02d", instructionCounter))
So that line in your code becomes something like this:

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) );

Producing output as:

REGISTERS:
accumulator          +0000
instructionCounter      00
instructionRegister  +0000
operationCode           00
operand                 00

Hope this helps!