java - 如何从一行整数中删除前导/尾随空格?

标签 java formatting

我必须以类似矩阵的方式打印出表格,每个数字的宽度都设置为 4(数字右对齐,并去掉每行的前导/尾随空格)。前 3 行如下所示:

1   2   3   4   5   6   7   8   9  10  11  12
2   4   6   8  10  12  14  16  18  20  22  24
3   6   9  12  15  18  21  24  27  30  33  36

这是我的代码:

public static void main (String[] args) {
    int i,j;
    for(i=1;i<=3;i++){
        for(j=1;j<=12;j++){
            System.out.format("%4d",i*j);
        }
        System.out.println();
    }
}   

在输出中,第一个整数移动了 3 个空格。如何去掉每行的前导/尾随空格?

最佳答案

假设您想要摆脱中间所有无用的空格,为什么不首先避免它们呢?

public static void main(String[] args) {
    int rows = 3, columns = 12;

    for (int i = 1; i <= rows; i++) {
        for (int j = 1; j <= columns; j++) {
            // figure out the max # of digits needed
            int necessaryDigits;
            if (rows * j < 10) {
                necessaryDigits = 1;
            } else if (rows * j < 100) {
                necessaryDigits = 2;
            } else if (rows * j < 1000) {
                necessaryDigits = 3;
            } else {
                necessaryDigits = 4;
            }
            // print them accordingly with one extra space to distinguish
            // the numbers and avoid the leading one in 1st column
            System.out.format("%" + (necessaryDigits + (j == 1 ? 0 : 1))
                    + "d", i * j);
        }
        System.out.println();
    }
}

输出:

1 2 3  4  5  6  7  8  9 10 11 12
2 4 6  8 10 12 14 16 18 20 22 24
3 6 9 12 15 18 21 24 27 30 33 36

输出或10行:

 1  2  3  4  5  6  7  8  9  10  11  12
 2  4  6  8 10 12 14 16 18  20  22  24
 3  6  9 12 15 18 21 24 27  30  33  36
 4  8 12 16 20 24 28 32 36  40  44  48
 5 10 15 20 25 30 35 40 45  50  55  60
 6 12 18 24 30 36 42 48 54  60  66  72
 7 14 21 28 35 42 49 56 63  70  77  84
 8 16 24 32 40 48 56 64 72  80  88  96
 9 18 27 36 45 54 63 72 81  90  99 108
10 20 30 40 50 60 70 80 90 100 110 120

关于java - 如何从一行整数中删除前导/尾随空格?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34672701/

相关文章:

php - 使用 PHP 格式化 HTTP POST 请求中的数据

Java .split 奇怪的结果

java - 在 Recycler View 中实现无限滚动

java - Mockito 在 Spy 上使用 doAnswer

java - 如何在另一个类中正确设置 onclicklistener?

Java Date异常处理try catch

JAVA - 使用通过其名称(字符串值)获得的类进行转换

vba - 使用VBA根据句子的起始字符改变文本的颜色

PHP邮件换行问题

java 基于模式的格式化字符串