Reputation: 11
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();
}
}
}
Upvotes: 0
Views: 112
Reputation: 152
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.
Upvotes: 1