I'm currently trying to use java to make a multitable with the following output:
0 1 2 3 4 5 6 7 8 9
+------------------------------
0| 0 0 0 0 0 0 0 0 0 0
1| 0 1 2 3 4 5 6 7 8 9
2| 0 2 4 6 8 10 12 14 16 18
3| 0 3 6 9 12 15 18 21 24 27
4| 0 4 8 12 16 20 24 28 32 36
5| 0 5 10 15 20 25 30 35 40 45
6| 0 6 12 18 24 30 36 42 48 54
7| 0 7 14 21 28 35 42 49 56 63
8| 0 8 16 24 32 40 48 56 64 72
9| 0 9 18 27 36 45 54 63 72 81
However, instead of the result above, i got this:
0 1 2 3 4 5 6 7 8 9
+-------------------------------------------
0| 0 0 0 0 0 0 0 0 0 0
1| 0 1 2 3 4 5 6 7 8 9
2| 0 2 4 6 8 10 12 14 16 18
3| 0 3 6 9 12 15 18 21 24 27
4| 0 4 8 12 16 20 24 28 32 36
5| 0 5 10 15 20 25 30 35 40 45
6| 0 6 12 18 24 30 36 42 48 54
7| 0 7 14 21 28 35 42 49 56 63
8| 0 8 16 24 32 40 48 56 64 72
9| 0 9 18 27 36 45 54 63 72 81
Therefore, i'd like to know is there any way the fix the problem? Thanks.
Here's the code.
import java.util.*;
public class MultiTable
{
public static void main(String[] args)
{
int x = 9;
System.out.print(" ");
for(int k = 0; k<=x ;k++ ) {
System.out.print( k + " ");
}
System.out.println("\n +-------------------------------------------");
for(int i = 0 ;i<=x ;i++) {
System.out.print(i+ "| ");
for(int j=0;j<=x ;j++) {
System.out.print(j*i + " ");
}
System.out.println();
}
System.out.println("\n");
System.out.println("\n\n");
}
}
Thanks.
Print formatted strings instead of printing it as-is.
Either you can print the formatted string directly to the output using System.out.printf()
or
You can format a string using String.format()
first, then print it using println
.
In your case, you need to force the integers to be at least 2 characters long. If the integer has too few digits, you can pad it in spaces. This is how you can do it:
int number = 1;
// printf approach
System.out.printf("%3d", number);
// Formatted string approach
String formatted = String.format("%3d", number);
System.out.print(formatted);
In the format, you can see %3d
. It means:
%
start the formatting3
right-align, 3 spaces (negative number will left-align). Im using 3 so that the numbers won't stick together.d
a decimal (base-10 integer) will be formattedYou can read more about formatters in Java's official docs