如何在for循环中从行尾删除空格

时间:2019-02-18 17:46:45

标签: java for-loop

问题是下一行,即每行的末尾,程序将写入一个空格。如何删除它?

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 个答案:

答案 0 :(得分:2)

有两种方法可以解决此问题。较干净的解决方案之一可能是使用Java的内置功能来连接Strings(我记得在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));
}

答案 1 :(得分: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();
}

答案 2 :(得分: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();
}

答案 3 :(得分:0)

System.out.print(i * j + ( j < 9 ? " ", "" )); 

当j小于9(最后一个)concat空间时,否则concat为空–