Reputation: 41
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++;
}
}
}
Upvotes: 1
Views: 230
Reputation: 12880
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!
Upvotes: 3
Reputation: 7324
Just Add the following line after while loop
System.out.print("\b");
Upvotes: 1
Reputation: 577
Try:
if(n1==n)
System.out.print(x);
else
if(n1 != n-1) {
System.out.print(x+" ");
} else {
System.out.print(x);
}
n1++;
Upvotes: 0