[英]How to make all the elements of a 2 dimensional array line up into a perfect table using printf -Java
我需要这个程序打印出一个最大10 * 10的乘法表。 我可以把它打印出来,我只是不知道如何使一切正常排列。 任何帮助表示赞赏!
public class multTable
{
private static final int TABLE_SIZE = 10;
public static void main(String[] args)
{
int table[][] = new int[TABLE_SIZE][TABLE_SIZE];
for (int r=1; r<=10; r++)
{
for (int c=1; c<=10; c++)
{
System.out.printf(" "+r*c);
}
System.out.println();
}
}
}
这是打印出来的:
1 2 3 4 5 6 7 8 9 10
2 4 6 8 10 12 14 16 18 20
3 6 9 12 15 18 21 24 27 30
4 8 12 16 20 24 28 32 36 40
5 10 15 20 25 30 35 40 45 50
6 12 18 24 30 36 42 48 54 60
7 14 21 28 35 42 49 56 63 70
8 16 24 32 40 48 56 64 72 80
9 18 27 36 45 54 63 72 81 90
10 20 30 40 50 60 70 80 90 100
System.out.printf(" "+ StringUtils.rightPad(String.valueOf(r*c),3));
代替
System.out.printf(" "+r*c);
要么
创建自己的rightPad
方法
private static String rightPad(String value, int length)
{
int size = value.length();
if (size == length)
{
return value;
}
else if (size > length)
{
return value.substring(0, length);
}
else
{
StringBuilder stringBuilder = new StringBuilder();
length = length - size;
stringBuilder.append(value);
for (int i = 0; i < length; i++)
{
stringBuilder.append(" ");
}
return stringBuilder.toString();
}
}
在for循环中替换它
System.out.format(" " + rightPad(String.valueOf((r * c)), 4)); // you may give any value you like 2,3,4,5...etc for length
输出:
1 2 3 4 5 6 7 8 9 10
2 4 6 8 10 12 14 16 18 20
3 6 9 12 15 18 21 24 27 30
4 8 12 16 20 24 28 32 36 40
5 10 15 20 25 30 35 40 45 50
6 12 18 24 30 36 42 48 54 60
7 14 21 28 35 42 49 56 63 70
8 16 24 32 40 48 56 64 72 80
9 18 27 36 45 54 63 72 81 90
10 20 30 40 50 60 70 80 90 100
使用tab作为分隔符
System.out.printf(r*c+"\t"); // \t stands for tab
然后你可以得到很好的表格输出
1 2 3 4 5 6 7 8 9 10
2 4 6 8 10 12 14 16 18 20
3 6 9 12 15 18 21 24 27 30
4 8 12 16 20 24 28 32 36 40
5 10 15 20 25 30 35 40 45 50
6 12 18 24 30 36 42 48 54 60
7 14 21 28 35 42 49 56 63 70
8 16 24 32 40 48 56 64 72 80
9 18 27 36 45 54 63 72 81 90
10 20 30 40 50 60 70 80 90 100
如果你打算仍然使用(c风格)printf,你可以使用它来确保它们全部对齐3位数:
System.out.printf("%3d ", r*c);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.