问题描述:

I wrote this in Java, and I want the output such that it creates a space after every value except for the last one. How do I get it to show up like 1[]2[]3[]4[]5[]6[]7 rather than 1[]2[]3[]4[]5[]6[]7[] ?

Here is my code!

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++;

}

}

}

网友答案:

Your code is perfectly fine. I see no problem with it. Just check this out

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

Replace this "\n"(new line) with " " (space) if you want!

网友答案:

Just Add the following line after while loop

System.out.print("\b");
网友答案:

Try:

if(n1==n)
    System.out.print(x);
else
    if(n1 != n-1) {
        System.out.print(x+" ");
    } else {
        System.out.print(x);
    }
n1++;
相关阅读:
Top