0

In Java, how could I use printf() to both left justify and right justify output on the same line consistently? This is the code for everything left justified:

System.out.println("   ********************L********R");
String[] array = {"apple", "pie", "cheese"};
double[] array2 = {0.003, 1245, 19.979};
double[] array3 = {0.2, 1, 9};
for (int index = 0; index < array.length; index++)
{
    System.out.printf("   %-10s%-10.2f%.2f%n", array[index], array2[index], array3[index]);
}

This is the output that everything is left justified:

   ********************L********R
   apple     0.00      0.20
   pie       1245.00   1.00
   cheese    19.98     9.00

What I want instead if that for the third elements (0.20, 1.00, 9.00) to be right justified. I indicated in the output above that "L" is left justified, but I want the variables to be right justified where the "R" is. How can I right justify the output on the right (0.20, 1.00, 9.00), while also keeping the output on the left (apple, pie, cheese) left justified?

1
  • Oh, I realized my mistake. I thought that putting %10.2f on the last column would start counting spaces from (0.00, 1245.00, 12.98) and since they were all of different lengths, I thought the third column would be off by one, two, three. I see now, that the -10.2f on the second column alligned evenly 10 spaces, so the third column would start after those 10 spaces. Thanks everyone! Commented Dec 19, 2014 at 4:55

2 Answers 2

1

Please refer to Formatting Numeric Print Output

Try System.out.format(" %-10s%-10.2f%10.2f%n")

Sign up to request clarification or add additional context in comments.

1 Comment

Try " %-10s%-10.2f%10.2f%n"
1

Your last parameter, %.2f, isn't specifying a number of characters to right justify. Assuming you want it to be 10 characters, like the other parameters, you'd probably want %10.2f.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.