wesleyNeill wesleyNeill - 2 months ago 5
Java Question

How and in what order do I combine printf formatting arguments for a single printed output consisting of Strings and doubles?

Good afternoon,

Here are three lines of java code that I would like to combine into a single printf statement. The idea is to eventually have several columns of evenly spaced data expressed in computer scientific notation with 5 significant digits. I can't seem to combine the arguments in the right order. Also, when I try to format multiple columns by adding extra "%-#s" formats, I am being told that I have not included enough arguments, or funny stuff comes out. What am I doing wrong?

System.out.printf("%-3s", "a_"+k+" = ");
System.out.printf("%6.3e\n", a_k[k]);
System.out.printf("%6.3e\n", a1_k[k]);


I have tried the below in various orders and combinations to no avail, and can't understand the javadocs on how to implement this correctly:

System.out.printf("%-3s%5.4e%-10s%5.4e\n", "a_"+k+" = ", a_k[k], a1_k[k]);


Thanks!

Answer

when I try to format multiple columns by adding extra "%-#s" formats, I am being told that I have not included enough arguments

It is expecting a third argument as a string.

Here are your four formats.

  1. %-3s
  2. %5.4e
  3. %-10s
  4. %5.4e

Therefore, just insert a ""

System.out.printf("%-3s%5.4e%-10s%5.4e\n", "a_"+k+" = ", a_k[k], "", a1_k[k]);

See example

Or, to make this easier on the eyes

String akEq = "a_"+k+" = ";
float col1 = a_k[k];
float col2 = a1_k[k];
System.out.printf("%-3s%5.4e%-10s%5.4e\n", akEq, col1, "", col2);