Formatting java strings with system.out.printf

I searched a lot of questions about System.out.printf in java for formatting string outputs, and I just don't understand how to use it.

I am trying to print nice columns that look like

601 GoPro Hero5 Black       276.95
602 GoPro Hero5 Session     199.00
611 Canon EOS Rebel         361.89

but the best I can get is

601 GoPro Hero5 Black     276.95
602 GoPro Hero5 Session     199.00
611 Canon EOS Rebel     361.89

It seems I can align the first two values, but never the third. Here is my code

System.out.printf("%-1s %10s %10.2f\n", "ex string", "ex string", 276.95);

I thought that “-1s” was left aligned for minus, and 1 would be the gap between the first and second input, then% 10s would be divided by ten characters,% 10.2 would be divided by ten with two decimal places. So I tried to do

System.out.printf("%-1s %10s %20.2f\n", "ex string", "ex string", 276.95);

but this still does not lead to the fact that these third values ​​are embedded in each other.


Revised attempt using

System.out.printf("%-10s %-10s %10.2f\n", "ex string", "ex string", 276.95);

leads to...

601        GoPro Hero5 Black     276.95
602        GoPro Hero5 Session     199.00
611        Canon EOS Rebel     361.89

for writing, my code receives the following variables:

System.out.printf("%-10s %-10s %10.2f\n", items.get(i).getItemNumber(), items.get(i).getName(), items.get(i).getPrice());
+4
1

.

%-1 . 3 , . : .

, %10 10 . , .

, - ,

%-4s%-25s%6.2f

:

  • 4
  • 25
  • , , 6

%4s %3s<space> . , . , 3 . .

+4

Source: https://habr.com/ru/post/1695631/


All Articles