最后删除额外空间

时间:2013-12-22 03:59:02

标签: java

我用Java编写了这个,我想要输出,以便在除了最后一个值之外的每个值之后创建一个空格。如何让它显示为1[]2[]3[]4[]5[]6[]7而不是1[]2[]3[]4[]5[]6[]7[]

这是我的代码!

public class Pentagonal {
    public static void main(String[] args) {
        int n, x, n1;

        Scanner input = new Scanner(System.in);
        System.out.print("Enter an integer: ");
        n = input.nextInt();

        n1 = 1;

        System.out.print("The pentagonal numbers are: ");

        while (n1 <= n) {
            x = (3 * n1 * n1 - n1) / 2;
            if (n1 == n)
                System.out.print(x);
            else
                System.out.print(x + " ");
            n1++;
        }
    }
}

3 个答案:

答案 0 :(得分:3)

你的代码非常好。我觉得没问题。请检查一下

 while (n1 <= n) {
    x = (3 * n1 * n1 - n1) / 2;
    System.out.print(x + ((n1 == n) ? "\n" : " "));
    n1++;
}

如果需要,请将此"\n"(新行)替换为" "(空格)!

答案 1 :(得分:1)

只需在while循环

之后添加以下行
System.out.print("\b");

答案 2 :(得分:0)

尝试:

if(n1==n)
    System.out.print(x);
else
    if(n1 != n-1) {
        System.out.print(x+" ");
    } else {
        System.out.print(x);
    }
n1++;