1

问题是接下来,在每一行的末尾,程序都会写一个空格。如何删除它?

public class Szorzotabla {

    public static void main(String[] args) {
        for (int i = 1; i < 10; i ++) {
            for (int j = 1; j < 10; j++) {
                System.out.print(i * j + " ");
            }
            System.out.println();
        }
    }

}

我希望乘法表的输出在每一行的末尾都没有空格。

4

4 回答 4

1

有几种方法可以解决这个问题。一种更简洁的解决方案可能是使用 Java 的内置功能来加入字符串(如果我记得的话,它是在 Java 8 中添加的)。

for (int i = 1; i < 10; i++) {
    String[] products = new String[9];
    for (int j = 1; j < 10; j++) {
        products[j-1] = String.valueOf(j * i);
    }
    System.out.println(String.join(" ", products));
}
于 2019-02-18T17:54:54.490 回答
1

您可以使用这种方式:

String space;
for (int i = 1; i < 10; i ++) {
    space = ""; // declare a variable here
    for (int j = 1; j < 10; j++) {
        System.out.print(space + i * j); // and note here to change the order
        space = " "; // after the first iteration set a space to the variable
    }
    System.out.println();
}
于 2019-02-18T17:52:34.780 回答
0
System.out.print(i * j + ( j < 9 ? " ", "" )); 

当 j 小于 9(最后一个)时 concat space else concat empty –</p>

于 2019-02-18T18:01:23.717 回答
0

你在行尾得到一个空格,因为你在每行的末尾打印一个空格,i*j即使每行的最后一个不需要一个空格。

相反,您可以更改它以便在之前 打印空格,并在进入内部循环之前i*j手动打印第一个没有空格的空格。i*j这样你的代码就保持相对干净。

for(int i = 1; i < 10; i ++) {
    System.out.print(i);
    for(int j = 2; j < 10; j++) { //start j at 2
        System.out.print(" " + i * j);
    }
    System.out.println();
}
于 2019-02-18T17:51:19.103 回答