0

I want to print columns using the formatting specifier with printf in Java. However I can't seem to get this right. I want the numbers to be aligned perfectly.

This is what I want to get: enter image description here

This is what I am getting: enter image description here

import java.util.Scanner;

public class LabTimeTable{

   public static void main(String [] args){
   Scanner input = new Scanner(System.in);

   System.out.println("Time Table:");

   System.out.print("Number (1-10): ");
   int number1 = input.nextInt();
   int number2 = (number1+1);

      for(int i = 1; i < 11; i++){

         System.out.printf("%2d * %d = %d", i, number1, (number1*i));
         System.out.printf("%12d * %3d = %d", i, number2, (number2*i));
         System.out.println();

      }


   }

}

1 Answer 1

1

I would recommend you to use something like this:

System.out.printf("%2d * %d = %-10d", i, number1, (number1*i));
System.out.printf("%d * %3d = %d", i, number2, (number2*i));
System.out.println();

Here I am using -10d, which allocates 10 letter spaces for the last number in the first column, it includes the number too. Also notice, I removed 12d from second column, because it will make even greater space between these two columns.

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

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.